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);
}
}
I am trying to load a file into a file instance which is located in my project
and
I wanted to export my project to a runnable JAR but it does not work anymore
This would suggest that the file you are trying to find is embedded within the Jar file.
So the short answer would be, don't. Use getClass().getResourceAsStream(path)
and use the resulting InputStream
instead
Embedded resources are not files, they are bytes stored in a Jar(Zip) file
You need use something more like...
private void mapLoader(String path) {
try (Scanner s = new Scanner(getClass().getResourceAsStream(path)) {
while (s.hasNext()) {
int character = Integer.parseInt(s.next());
this.getMap().add(character);
}
} catch (IOException e) {
System.err.println("The map could not be loaded.");
e.printStackTrace();
}
}