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.

wattostudios
  • 8,666
  • 13
  • 43
  • 57
Guo Toby
  • 1
  • 3

3 Answers3

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.

Community
  • 1
  • 1
asgs
  • 3,928
  • 6
  • 39
  • 54
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.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • The absolute path is C:\Users\Name\workspace\Test\highScore.txt which is exactly where I put it. Now what? – Guo Toby Jun 16 '12 at 06:21
  • 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) – Bohemian Jun 16 '12 at 13:20
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);
    }
}
Jan Galinski
  • 11,768
  • 8
  • 54
  • 77
  • Forgot to give credit to Adam Bien for this one: http://www.adam-bien.com/roller/abien/entry/reading_a_file_into_a2 – Jan Galinski Jun 16 '12 at 17:54