【问题标题】:NoSuchFileException error while executing jar file执行 jar 文件时出现 NoSuchFileException 错误
【发布时间】:2019-04-29 19:51:49
【问题描述】:

我编写了一个读取文本文件的方法,当我运行它时它可以工作,但是当我执行 jar 时,我得到 NoSuchFileException 错误。 这是我的代码:

private static final String textFile = "textFile.txt";

    public readText() {
    try {
        regex = new String(Files.readAllBytes(Paths
                .get(textFile)))
                .replaceAll("\\r", "").split("\n");
    } catch (final IOException e) {
        e.printStackTrace();
    }
}

有人能指出我哪里出错了或者我应该做些什么改变吗?

【问题讨论】:

  • 您的jar 中有“textFile.txt”吗?如果有,在哪里?
  • 我解压后检查了jar文件,里面没有文本文件。
  • 文本文件中有什么内容?它是您提供给应用程序使用的资源吗?如果是这样,它应该被打包在 Jar 中,并且不能作为File 访问。
  • 文本文件包含我稍后用于比较的单词。
  • 让程序在运行时输出文本文件的位置——你很快就会明白为什么它会给你一个错误。

标签: java exception null


【解决方案1】:

我想出了一个办法:

try {
        InputStream in = getClass().getResourceAsStream(textFile);
        StringBuilder content = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line = reader.readLine();
        while(line!=null){
            content.append(line).append(System.lineSeparator());
            line = reader.readLine();
        }
        regex = content.toString()
                .replaceAll("\\r", "").split("\n");
    } catch (final IOException e) {
        e.printStackTrace();
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 2019-10-31
    • 2012-07-28
    • 2015-02-09
    相关资源
    最近更新 更多