How to read a text file inside a JAR? [duplicate]

柔情痞子 提交于 2019-11-29 10:24:52

You cannot use File inside a JAR file. You need to use InputStream to read the text data.

BufferedReader txtReader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/resources/mytextfile.txt")));

// ... Use the buffered reader to read the text file.

Try the next (with the full path package):

InputStream inputStream = ClassLoader.getSystemClassLoader().
        getSystemResourceAsStream("com/company/resources/howto.txt");
InputStreamReader streamReader = new InputStreamReader(inputStream, "UTF-8");
BufferedReader in = new BufferedReader(streamReader);

for (String line; (line = in.readLine()) != null;) {
    // do something with the line
}

You code will not compile. Class.getResource() returns a URL, and File has no constructor with a URL as an argument.

You can just use .getResourceAsStream() instead, it returns an InputStream directly, you just have to read the contents of the file from that stream.

Note: both of these methods return null if the resource is not found: don't forget to check for that...

Andrew Thompson

the contents of the text file will be added to an JEditorPane.

See DocumentVewer & especially JEditorPane.setPage(URL).

Since the help is an it will be necessary to gain an URL using getResource(String) as detailed in the info. page.

.. tried this: URL url = this.getClass().getResource("resources/howto.txt");

Change:

URL url = this.getClass().getResource("resources/howto.txt");

To:

URL url = this.getClass().getResource("/resources/howto.txt");  // note leading '/'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!