2017-04-11 79 views
0

我不明白为什么我不断收到FileNotFoundException? 我通过Eclipse使用Java,并试图读取一个整数的file.txt,我想将它们加在一起来测试它们,但不断得到异常。为什么我不断收到FileNotFoundException?

我已经将文件导入到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) 
+0

因为文件没有项目的目录中存在的异常被抛出。 –

回答

0
(new File("lab1_data.txt")); 

传递精确的目录路径 /文件夹名称/ lab1_data.txt

+0

我一直试图做到这一点,我得到了像C:\ xxx \ Desktop \ CS \ Labs \ src \ lab1_data.txt这样的东西,并且我会得到相同的异常。然后,我在eclipse中右键单击文件,并看到斜线正好相反,例如/Lab/src/lab1_data.txt。我改变了斜杠并修复了一切。 –

0

lab1_data.txt应该在类路径中找到。阅读文件的更好的方法是getResourceAsStream。简单的谷歌搜索应该有所帮助。

0

检查文件存在的位置,并在new File("...")处添加文件的完整路径。

请注意,当前项目路径并不总是与.java文件相同的路径。

0

此代码的工作

 String path=""; 
     File f=new File("lab1_data.txt"); 
     path=f.getAbsolutePath(); 
相关问题