Problem with relative file path

Posted by Richard Knop on Stack Overflow See other posts from Stack Overflow or by Richard Knop
Published on 2010-05-18T19:54:31Z Indexed on 2010/05/18 20:10 UTC
Read the original article Hit count: 294

Filed under:
|
|

So here is my program, which works ok:

import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.Locale;

public class ScanSum {
    public static void main(String[] args) throws IOException {
        Scanner s = null;
        double sum = 0;
        try {
            s = new Scanner(new BufferedReader(new FileReader("D:/java-projects/HelloWorld/bin/usnumbers.txt")));
            s.useLocale(Locale.US);

            while (s.hasNext()) {
                if (s.hasNextDouble()) {
                    sum += s.nextDouble();
                } else {
                    s.next();
                }
            }
        } finally {
            s.close();
        }

        System.out.println(sum);
    }
}

As you can see, I am using absolute path to the file I am reading from:

s = new Scanner(new BufferedReader(new FileReader("D:/java-projects/HelloWorld/bin/usnumbers.txt")));

The problem arises when I try to use the relative path:

s = new Scanner(new BufferedReader(new FileReader("usnumbers.txt")));

I get an error:

Exception in thread "main" java.lang.NullPointerException
    at ScanSum.main(ScanSum.java:24)

The file usnumbers.txt is in the same directory as the ScanSum.class file:

D:/java-projects/HelloWorld/bin/ScanSum.class
D:/java-projects/HelloWorld/bin/usnumbers.txt

How could I solve this?

© Stack Overflow or respective owner

Related posts about java

Related posts about eclipse