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.
thanks to @EJP and @immibis for all help.
was the solution that finally got me running