首页 > 解决方案 > 执行 jar 文件时出现 NoSuchFileException 错误

问题描述

我编写了一个读取文本文件的方法,当我运行它时它可以工作,但是当我执行 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();
    }
}

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

标签: javaexceptionnull

解决方案


我想出了一个办法:

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();
    }

推荐阅读