Where does Java put resource files when I JAR my program?

前端 未结 3 501
一向
一向 2021-01-20 23:26

Been looking for this for the past 2 hours and can\'t find anything (I\'ve found solutions to the same problem but with images, not text files).

Pretty much, I made a pr

3条回答
  •  情话喂你
    2021-01-20 23:43

    To the point, the FileReader can only read disk file system resources. But a JAR contains classpath resources only. You need to read it as a classpath resource. You need the ClassLoader for this.

    Assuming that Foo is your class in the JAR which needs to read the resource and items.txt is put in the classpath root of the JAR, then you should read it as follows (note: leading slash needed!):

    InputStream input = Foo.class.getResourceAsStream("/items.txt");
    reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
    // ...
    

    Or if you want to be independent from the class or runtime context, then use the context class loader which operates relative to the classpath root (note: no leading slash needed!):

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    InputStream input = classLoader.getResourceAsStream("items.txt");
    reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
    // ...
    

    (UTF-8 is of course the charset the file is encoded with, else you may see Mojibake)

提交回复
热议问题