简体   繁体   English

执行jar文件时出现NoSuchFileException错误

[英]NoSuchFileException error while executing jar file

I coded up a method which reads a text file, when I run it it works, but when I execute the jar, I get the NoSuchFileException error. 我编写了一个读取文本文件的方法,当我运行它时它可以工作,但是当我执行jar时,出现了NoSuchFileException错误。 Here is my code: 这是我的代码:

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

Could someone point out where am I going wrong or what changes I'm supposed to make? 有人可以指出我要去哪里或应该做哪些更改?

I figured out a way: 我想出了一种方法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM