I don't understand why I keep getting a FileNotFoundException? I am using java through Eclipse and am trying to read a file.txt of integers and I want to add them together to test them but keep getting the exception.
I have imported the file into eclipse. Here is my code and the exception messages I am getting.
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"));
传递确切的目录路径/文件夹名称/lab1_data.txt
lab1_data.txt should be in classpath to be found. Better appraoach to read the files is getResourceAsStream . A simple google search should help.
check where the file exists and add a full path to the file at new File("...")
.
be aware that the current project path not always the same path where your .java files are.
This Code Works
String path="";
File f=new File("lab1_data.txt");
path=f.getAbsolutePath();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.