相对文件路径问题
所以这是我的程序,它工作正常:
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);
}
}
如您所见,我正在使用我正在读取的文件的绝对路径:
s = new Scanner(new BufferedReader(new FileReader("D:/java-projects/HelloWorld/bin/usnumbers.txt")));
当我尝试使用相对路径时出现问题:
s = new Scanner(new BufferedReader(new FileReader("usnumbers.txt")));
我收到一个错误:
Exception in thread "main" java.lang.NullPointerException
at ScanSum.main(ScanSum.java:24)
文件 usnumbers.txt 与 ScanSum.class 文件位于同一目录中:
D:/java-projects/HelloWorld/bin/ScanSum.class
D:/java-projects/HelloWorld/bin/usnumbers.txt
我该如何解决这个问题?