Question

I am using scanner class in java5, and the following code will throw an exception:

Scanner scanner = new Scanner
        (new File(args[0]));
int dealId;
while (scanner.hasNextLine()) {
    dealId = scanner.nextInt();
    System.out.println(dealId);
}
scanner.close();

The stacktrace is:

Exception in thread "main" java.lang.NullPointerException
   at java.util.regex.Matcher.toMatchResult(libgcj.so.10)
   at java.util.Scanner.myCoreNext(libgcj.so.10)
   at java.util.Scanner.myPrepareForNext(libgcj.so.10)
   at java.util.Scanner.myNextLine(libgcj.so.10)
   at java.util.Scanner.hasNextLine(libgcj.so.10)

Does anybody knows what caused this exception?

Was it helpful?

Solution

The GCJ Home Page suggest it "supports most of the 1.4 libraries plus some 1.5 additions. "

Scanner was added in version 1.5 and I suspect you have hit a piece of functionality GCJ doesn't support. You need to try something different to see what you can get to work.

Is there any reason you are not using OpenJDK/Oracle Java 6 or 7? (Please don't say its for performance reasons ;)

OTHER TIPS

I reproduced the error and found a work around

Here is the code, compiled on x86_64 GNU/Linux, Fedora with Java 1.5.0:

Scanner r = new Scanner(f, "ISO-8859-1");
while(r.hasNext()){
    String line = r.nextLine();   //The guts of nextLine(), specifically: 
                                  //Matcher.toMatchResult bubbles up a 
                                  //nullPointerException
}

The file just contains two ascii words separated by a newline. The runtime Exception only occurs when nextLine processes the last line of the file, whether it has characters or not:

java.lang.NullPointerException
   at java.util.regex.Matcher.toMatchResult(libgcj.so.10)
   at java.util.Scanner.myCoreNext(libgcj.so.10)
   at java.util.Scanner.myPrepareForNext(libgcj.so.10)
   at java.util.Scanner.myNextLine(libgcj.so.10)
   at java.util.Scanner.nextLine(libgcj.so.10)
   at Main.parseFile(Main.java:1449)
   at Main.construct(Main.java:1420)
   at Main.populateBlogPosts(Main.java:1399)
   at Main.main(Main.java:263)

Here is a bug report on this issue: https://bugs.openjdk.java.net/browse/JDK-6178785

Diagnosis

It's a bug in libgcj.so.10, perfectly legitimate ascii input as well as blankstring causes it to puke an NPE on the last line of a file.

Workaround

Since this bug only occurs on the very last line of the file, the hacky workaround is to initially make sure there is at least one newline at the end of the file, then catch and ignore the nullPointerException bubbled up from toMatchResult and exit the loop when that happens.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top