Read text file that is not in the main package in a runnable jar

空扰寡人 提交于 2019-12-11 00:50:02

问题


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


回答1:


// added leading / to indicate search from root of class-path
String file = "/res/JSON_type2/file.txt";
InputStream is = this.getClass().getResourceAsStream(file);



回答2:


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.




回答3:


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").



来源:https://stackoverflow.com/questions/10286116/read-text-file-that-is-not-in-the-main-package-in-a-runnable-jar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!