Getting txt from jar & stucked

穿精又带淫゛_ 提交于 2019-12-23 01:51:28

问题


I currently started programming a board game playground which can load different games. I store these games in file named config.txt, but I am having trouble accessing it. Firstly, I started with my favourite file approach:

String fileAddress = "./resources/config.txt";
fis = new FileInputStream(fileAddress);
reader = new BufferedReader(new InputStreamReader(fis));

But then when I built .jar file, it stopped working. For obvious reasons. So I found myself looking around and I found about recommendation to use getResourceAsStream(String s) method. So I changed my code to following way:

String fileAddress = "./resources/config.txt";
InputStream toReturn=null;
toReturn = this.getClass().getClassLoader().getResourceAsStream(fileAddress);

But here I got stuck. No matter how I tweak the fileAddress (tried ./config.txt ./resources/config.txt ./resources/boardgames/config.txt and ./resources/boardgames/config.txt) and both using or omitting getClassLoader(), the result of toReturn just always equals NULL and ends up throwing NullPointerException very soon.

Location of required file follows. As I do not have enough reputation, I will have to ASCII art the file hierarchy. Both config.txt are valid targets.

On File System:

Boardgames
   src
   cache
   classes
   resources
      boardgames
         config.txt
      imgs
      config.txt

Inside Jar File

BoardGames.jar
    boardgames
       <class files>
       config.txt
    imgs
    META-INF
    config.txt

Therefore I would need an assistance with repairing the code so that it would read the file properly. If you could include tips how to get ImageIcon from the .png files located in subfolders imgs, since I reckon I will run into similar problem once I get past the initialization phase via config.txt.

Thank you for all your help.


回答1:


thanks to @EJP and @immibis for all help.

this.getClass().getResourceAsStream("boardgames/config.txt");

was the solution that finally got me running



来源:https://stackoverflow.com/questions/29268508/getting-txt-from-jar-stucked

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