I am trying to load a file into a file instance which is located in my project. When running in Eclipse I could do it like this:
File file = new File(path);
I wanted to export my project to a runnable JAR but it does not work anymore. Java throws a NullPointerException
when I do it the Eclipse way. After a couple hours of googling I found this:
File file = new File(ClassLoader.getSystemResource(path).getFile());
But this did not fix the problem. I still get the same NullPointerException. Here is the method where I would need this file:
private void mapLoader(String path) {
File file = new File(ClassLoader.getSystemResource(path).getFile());
Scanner s;
try {
s = new Scanner(file);
while (s.hasNext()) {
int character = Integer.parseInt(s.next());
this.getMap().add(character);
}
} catch (FileNotFoundException e) {
System.err.println("The map could not be loaded.");
}
}
Is there a way to load the file with the getResource() method? Or should I rewrite my mapLoader method completely?
EDIT: I changed my method to this and it worked thanks to @madprogrammer
private void mapLoader(String path) {
Scanner s = new Scanner(getClass().getResourceAsStream(path));
while (s.hasNext()) {
int character = Integer.parseInt(s.next());
this.getMap().add(character);
}
}