Issue
I have tried this in many ways, and followed several online instructions, such as this - Eclipse exported Runnable JAR not showing images But so far, no success.
I have a very simple program that reads a text file (test.txt) and prints out its contents to standard output. I am using Eclipse. Here is what I have done-
- I put the text file into a folder called 'resources'
- I right-clicked the resources folder, selected "Build path" and hit "Use as resource folder"
- In my code, I tried two ways of addressing the file - (a) as "/test.txt" and (b) as "resources/test.txt. The latter method works when I run the program within Eclipse. However, neither method works when I export the project as a runnable jar file. The resource folder fails to be included in the jar file.
Any help will be much appreciated.
Addendum: Here is the code.
public class FileIOTest {
public static void main(String[] args) {
String line;
try {
BufferedReader br = new BufferedReader(new FileReader(new File("/test.txt")));
while((line = br.readLine()) != null){
System.out.println(line);
}
br.close();
}
catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
}
}
Solution
You can not access a resource in a Jar file through a FileReader
because it is not a file on the file system. Java does have a mechanism for accessing resources in your classpath (including in Jars): ClassLoader.getResourceAsStream(). You can use it with your default classloader:
BufferedReader br = new BufferedReader(new InputStreamReader(
ClassLoader.getSystemClassLoader()
.getResourceAsStream("test.txt")));
Note that getResourceAsStream
returns null
instead of throwing an exception, so you may want to get the stream first, check if for null
, then either throw an exception or process it.
You will want to give the full path within the jar as your path.
Answered By - Mad Physicist
Answer Checked By - Clifford M. (JavaFixing Volunteer)