简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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