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
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
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.
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)
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
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"
.
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()