0

I am trying to access High_Scores.txt file stored in folder Resources.

My project tree looks like this:

Project Tree

I am using the code shown below to access the file. Checked this similar question but the solutions are not working in my case.

File file = new File(getClass().getClassLoader().getResource("/Resources/High_Scores.txt").getFile());

But I keep on getting NULLPointerException. I do not understand this exception clearly in this context. Can someone point out what I am doing wrong?

Update:

If I alter the code to this:

File file = new File(getClass().getClassLoader().getResource("Resources/High_Scores.txt").getFile());

I get FILENOTFOUNDException.

Community
  • 1
  • 1
Mohsin Anees
  • 698
  • 2
  • 9
  • 25
  • @Tunaki This question is follow up to that question. Can't you see I have tried that question's answer but still face an issue. – Mohsin Anees Aug 29 '16 at 20:18
  • You cannot access a resource that is inside a JAR as a `File` like you're trying here, this simply can't work. You have to use an `InputStream`, as shown in the linked question. – Tunaki Aug 29 '16 at 20:20
  • Thank you. Now you should have answered this question like that instead of marking duplicate -.- – Mohsin Anees Aug 29 '16 at 20:24
  • Ah I could have indeed, but there's no point in duplicating content. It is preferable to refer to a question instead of repeating the same things. – Tunaki Aug 29 '16 at 20:25

1 Answers1

0

For reading file you can use InputStream instead of new File() like this (Let assume you are calling to read file From Board class)

InputStream stream = Board.class.getResourceAsStream("/Resources/high.txt");
    BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
    StringBuilder out = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        out.append(line);
    }
    System.out.println(out.toString());   //Prints the string content read from input stream
    reader.close();

or you can use ClassLoader Object

File file = new File(ClassLoader.getSystemResource("/Resources/high.txt").getFile());

if specific directories contain folder

File file = new File(ClassLoader.getSystemResource("/Resources/high.txt").toURI());
Bibek Shakya
  • 1,233
  • 2
  • 23
  • 45