代码之家  ›  专栏  ›  技术社区  ›  gangwerz

引发IOException后找不到文件

  •  -1
  • gangwerz  · 技术社区  · 11 年前

    当我尝试从文件中读取时,会出现以下异常:

    ERROR:
    Exception in thread "main" java.io.FileNotFoundException: newfile.txt (No such file or directory)
        at java.io.FileInputStream.open(Native Method)
        at java.io.FileInputStream.<init>(FileInputStream.java:138)
        at java.util.Scanner.<init>(Scanner.java:611)
        at Postal.main(Postal.java:19)
    


    import java.util.Scanner;
    import java.io.*;
    
    public class Postal   { 
    
        public static void main(String[] args) throws Exception   {
            /*** Local Variables ***/
            String line;
            Scanner filescan;
            File file = new File("newfile.txt");
            filescan = new Scanner(file);
            userInfo book = new userInfo();
    
            /*** Loop through newfile.txt ***/
            while (filescan.hasNext())   {
              line = filescan.nextLine();
              book.addNew(line);
            }
    
            book.print(0);
        }
    
    }
    
    3 回复  |  直到 11 年前
        1
  •  0
  •   Crigges    11 年前

    班级 Scanner 使用 FileInputStream 读取文件内容。 但它找不到该文件,因此引发了异常。 您正在使用文件的相对路径,请尝试使用绝对路径。

        2
  •  0
  •   Malik Brahimi    11 年前

    请改用此选项:

    File file = new File(getClass().getResource("newfile.txt"));
    
        3
  •  -1
  •   spooky    11 年前

    提供要创建文件的位置的绝对路径。并检查用户是否有权在那里创建文件。找到路径的一种方法是:

    File f = new File("NewFile.txt");
    if (!f.exists()) {
        throw new FileNotFoundException("Failed to find file: " + 
            f.getAbsolutePath());
    }
    

    尝试此操作打开文件:

    File f = new File("/path-to-file/NewFile.txt");