14

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?

1
  • Can you please mark line number 24 in your source?
    – tangens
    May 18, 2010 at 19:56

7 Answers 7

29

If aioobe@'s suggestion doesn't work for you, and you need to find out which directory the app is running from, try logging the following:

new File(".").getAbsolutePath()
2
  • 2
    +1 for showing the way to find out where the app is running from. Thanks!
    – Vikram
    Oct 18, 2014 at 22:53
  • 2
    No problem--glad it was useful to someone after all this time :)
    – pdbartlett
    Oct 20, 2014 at 14:13
16

From which directory is the class file executed? (That would be the current working directory and base directory for relative paths.)

If you simply launch the application from eclipse, the project directory will be the working directory, and you should in that case use "bin/usnumbers.txt".

1
  • 3
    As a side note, putting your application and its files in a JAR file and using the Class's getResourceAsStream method avoids this problem. s = new Scanner(ScanSum.class.getResourceAsStream("usnumbers.txt"));
    – Powerlord
    May 18, 2010 at 20:25
5

The NullPointerException is due to the fact that new FileReader() expression is throwing a FileNotFoundException, and the variable s is never re-assigned a non-null value.

The file "usnumbers.txt" is not found because relative paths are resolved (as with all programs) relative to the current working directory, not one of the many entries on the classpath.

To fix the first problem, never assign a meaningless null value just to hush the compiler warnings about unassigned variables. Use a pattern like this:

FileReader r = new FileReader(path);
try {
  Scanner s = new Scanner(new BufferedReader(r));
  ...
} finally {
  r.close();
}

For the second problem, change directories to the directory that contains "usnumbers.txt" before launching java. Or, move that file to the directory from which java is run.

3

It must be a FileNotFoundException causing NPE in the finally block. Eclipse, by default, executes the class with the project folder (D:/java-projects/HelloWorld in your case ) as the working directory. Put the usnumbers.txt file in that folder and try. Or change the working directory in Run Configuration -> Argument tab

1

Since your working directory is “D:/java-projects/HelloWorld”

@pdbartlett's id is great, But String filePath = new File(".").getAbsolutePath() will output "D:/java-projects/HelloWorld/." which is not easy to add your extra relative path like "filePath" + "/src/main/resources/" + FILENAME which located in resources folder.

I suggest with String filePath = new File("").getAbsolutePath() which return the project root folder

0

In Eclipse, you can also look under "Run Configurations->Than TAB "Classpath".

By default the absolut path is listed under "User Entries" in [icon] 'your.path' (default classpath)

0

Put the file in resources folder.

ClassLoader classLoader = getClass().getClassLoader();
String file1 = classLoader.getResource("myfile.csv").getPath(); 

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.