为什么我总是收到 FileNotFoundException?
why am I keep getting a FileNotFoundException?
我不明白为什么我总是收到 FileNotFoundException?
我正在通过 Eclipse 使用 java 并尝试读取 file.txt 个整数,我想将它们加在一起以测试它们但不断出现异常。
我已经将文件导入eclipse。
这是我的代码和我收到的异常消息。
public class FileRead {
//fields
private Scanner s;
private int[] arr;
/**
* @throws FileNotFoundException
*
*/
public FileRead() throws FileNotFoundException{
s = new Scanner(new File("lab1_data.txt"));
arr = new int[10000000];
for(int i = 0;i < arr.length;i++){
arr[i] = s.nextInt();
}
}
public int addArr(){
int a = 0;
for(int x: arr){
a = a + x;
}
return a;
}
/**
* @param args
*/
public static void main(String[] args) {
FileRead r = null;
try {
r = new FileRead();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
r.addArr();
}
}
java.io.FileNotFoundException: lab1_data.txt (The system cannot find the
file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at FileRead.<init>(FileRead.java:22)
at FileRead.main(FileRead.java:44)
Exception in thread "main" java.lang.NullPointerException
at FileRead.main(FileRead.java:48)
(new File("lab1_data.txt"));
传递准确的目录路径
/文件夹 name/lab1_data.txt
lab1_data.txt 应该在要找到的类路径中。读取文件的更好方法是 getResourceAsStream。简单的 google 搜索应该会有帮助。
检查文件存在的位置并在 new File("...")
.
添加文件的完整路径
请注意,当前项目路径并不总是与您的 .java 文件所在的路径相同。
此代码有效
String path="";
File f=new File("lab1_data.txt");
path=f.getAbsolutePath();
我不明白为什么我总是收到 FileNotFoundException? 我正在通过 Eclipse 使用 java 并尝试读取 file.txt 个整数,我想将它们加在一起以测试它们但不断出现异常。
我已经将文件导入eclipse。 这是我的代码和我收到的异常消息。
public class FileRead {
//fields
private Scanner s;
private int[] arr;
/**
* @throws FileNotFoundException
*
*/
public FileRead() throws FileNotFoundException{
s = new Scanner(new File("lab1_data.txt"));
arr = new int[10000000];
for(int i = 0;i < arr.length;i++){
arr[i] = s.nextInt();
}
}
public int addArr(){
int a = 0;
for(int x: arr){
a = a + x;
}
return a;
}
/**
* @param args
*/
public static void main(String[] args) {
FileRead r = null;
try {
r = new FileRead();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
r.addArr();
}
}
java.io.FileNotFoundException: lab1_data.txt (The system cannot find the
file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(Unknown Source)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at FileRead.<init>(FileRead.java:22)
at FileRead.main(FileRead.java:44)
Exception in thread "main" java.lang.NullPointerException
at FileRead.main(FileRead.java:48)
(new File("lab1_data.txt"));
传递准确的目录路径 /文件夹 name/lab1_data.txt
lab1_data.txt 应该在要找到的类路径中。读取文件的更好方法是 getResourceAsStream。简单的 google 搜索应该会有帮助。
检查文件存在的位置并在 new File("...")
.
请注意,当前项目路径并不总是与您的 .java 文件所在的路径相同。
此代码有效
String path="";
File f=new File("lab1_data.txt");
path=f.getAbsolutePath();