0

I tried this:

  InputStream file = Test.class.getResourceAsStream("highScore.txt");
  BufferedReader br = new BufferedReader (new InputStreamReader(file));
  String text;
  text = br.readLine();
  while (text!=null) {
    System.out.println (text);
  }

but I get NullPointerException error.

5
  • 3
    are you sure highScore.txt exists on your classpath? Commented Jun 16, 2012 at 6:00
  • 3
    Where exactly is the NPE thrown? Commented Jun 16, 2012 at 6:01
  • You mean where the error occurs? It occurs at BufferedReader br = new BufferedReader (new InputStreamReader(file)); Commented Jun 16, 2012 at 6:04
  • 1
    Try adding a slash / to the resource name: Test.class.getResourceAsStream("/highScore.txt"); Commented Jun 16, 2012 at 6:07
  • On which line are you getting a NullPointerException? Commented Jun 16, 2012 at 6:11

3 Answers 3

2

The resource you're trying to read as an InputStream should exist on your Java Classpath. Otherwise getResourceAsStream() would return null, leading to NullPointerException when you try to create an InputStreamReader out of it. See different-ways-of-loading-a-file-as-an-inputstream on how to read a resource.

Sign up to request clarification or add additional context in comments.

Comments

2

Try a simple file instead:

InputStream file = new FileInputStream("highScore.txt");

Edited

If you are having problems getting the path right, do this:

System.out.println(new File("highScore.txt").getAbsolutePath());

That will quickly tell you what the "current" directory is. You might find you need to use "../highScore.txt" if you need to go up one directory level, or "/somedir/highScore.txt" if you need to go down, etc.

I find printing the absolute path is the quickest way to resolve these kinds of problems.

2 Comments

The absolute path is C:\Users\Name\workspace\Test\highScore.txt which is exactly where I put it. Now what?
Then your FileNotFoundException has nothing to do with that file. Maybe there's somewhere else in your code that you're using a file that isn't there (cos this one is there)
0

You can use this one-liner for file-to-string

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ScannerSample {

    public static void main(String[] args) throws FileNotFoundException {
     //Z means: "The end of the input but for the final terminator, if any"
        String output = new Scanner(new File("file.txt")).useDelimiter("\\Z").next();
        System.out.println("" + output);
    }
}

1 Comment

Forgot to give credit to Adam Bien for this one: adam-bien.com/roller/abien/entry/reading_a_file_into_a2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.