Reputation: 77
I have a Swing Java program that reads *.txt files in a resource folder called 'res' containing subfolders of different kind of JSONs. When I run directly from Eclipse, all is fine. If I create an executable jar it doesn't work. I managed to make it work with an horrifying solution, putting all my text files in the package where they are called.
To read them I use this line of code:
InputStream is = this.getClass().getResourceAsStream(file + ".txt");
where file is a string. I thought this would search in the jar the specified file but obviously not. I tried to put the path to the files, res/subfolder/name_of_file.txt and subfolder/name_of_file.txt but to no avail. Here is the structure of my project
Project
src
com.package
res
JSON_type1
JSON_type2
file.txt
From com.package, I have a class that must read from JSON_type2/file.txt. Besides the obvious reason to keep my text file organized in the subfolders is that my GUI will populates a drop down list with the content of those subfolders.
From what I've gather from other questions here, getResourceAsStream() would have been my solution if I wanted to keep my text files in the package where they are called. Other than that I found something about subclassing ClassLoader and overwriting findResource(). If possible I want to avoid this solution as I'm far from being familiar with that class and its functionalities.
Should you need more informations, let me know.
Thank you
P.S.: This question arose from my previous question here
Upvotes: 2
Views: 2261
Reputation: 11
I was able to get basically the functionality you are looking for in Eclipse by doing this:
src (folder)
main (package)
...Classes...
other (folder)
res (package)
...txt files...
It seems that Eclipse completely ignores folders and only cares about packages. As long as I put my text files in a package, I am able to grab an InputStream with getResourceAsStream("/res/somefile.txt").
Upvotes: 1
Reputation: 168825
// added leading / to indicate search from root of class-path
String file = "/res/JSON_type2/file.txt";
InputStream is = this.getClass().getResourceAsStream(file);
Upvotes: 4
Reputation: 4704
You can address files in the packages by dividing them with slashes, for example for file.txt you should getResourceAsStream("/res/JSON_type2/file.txt")
The slashes are not for folder stucture and not platform dependant, they're just the way the classloader addresses files.
Upvotes: 4