0

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);
    }
}
Aruloci
  • 589
  • 4
  • 18

1 Answers1

0

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();
    }
}
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
  • I don't think I understood what you meant. Did you suggest something like this? File file = new File(getClass().getResourceAsStream(path)); – Aruloci May 28 '15 at 06:08
  • No, you can't access the resource as `File` any more, I meant something more like `s = new Scanner(getClass().getResourceAsStream(path))`. You can't think of embedded resources like files, they simply aren't, they are entries within a Jar/Zip file – MadProgrammer May 28 '15 at 06:11