Reading File In JAR using Relative Path

后端 未结 1 907
旧时难觅i
旧时难觅i 2020-12-14 13:30

I have some text configuration file that need to be read by my program. My current code is:

protected File getConfigFile() {
    URL url = getClass().getRes         


        
相关标签:
1条回答
  • 2020-12-14 13:40

    When the file is inside a jar, you can't use the File class to represent it, since it is a jar: URI. Instead, the URL class itself already gives you with openStream() the possibility to read the contents.

    Or you can shortcut this by using getResourceAsStream() instead of getResource().

    To get a BufferedReader (which is easier to use, as it has a readLine() method), use the usual stream-wrapping:

    InputStream configStream = getClass().getResourceAsStream("wof.txt");
    BufferedReader configReader = new BufferedReader(new InputStreamReader(configStream, "UTF-8"));
    

    Instead of "UTF-8" use the encoding actually used by the file (i.e. which you used in the editor).


    Another point: Even if you only have file: URIs, you should not do the URL to File-conversion yourself, instead use new File(url.toURI()). This works for other problematic characters as well.

    0 讨论(0)
提交回复
热议问题