I am using
File file = new File("res/movies.txt");
to read text from a bundled .txt file. My code works perfectly when running the program within IntelliJ IDEA, but when I create a .jar file and run it, it gives a "File not found" error. What can I do to make the code work both in the IDE as well as in the jar file?
You need to load the file as a resource. You can use Class.getResourceAsStream
or ClassLoader.getResourceAsStream
; each will give return an InputStream
for the resource.
Once you've got an InputStream
, wrap it in an InputStreamReader
(specifying the appropriate encoding) to read text from it.
If you need to sometimes read from an arbitrary file and sometimes read from a resource, it's probably best to use separate paths to either create a FileInputStream
for the file or one of the methods above for a resource, then do everything else the same way after that.
Here's an example which prints each line from resources/names.txt
which should be bundled in the same jar file as the code:
package example;
import java.io.*;
import java.nio.charset.*;
public class Test {
public static void main(String[] args) throws IOException {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
Test.class.getResourceAsStream("/resources/names.txt"),
StandardCharsets.UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
}
}
See more on this question at Stackoverflow