执行jar文件时出现NoSuchFileException错误

时间:2018-11-28 00:40:42

标签: java exception null

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

有人可以指出我要去哪里哪里或应该做些什么改变吗?

1 个答案:

答案 0 :(得分:0)

我想出了一种方法:

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();
    }
相关问题