【问题标题】:File Not Found w/ FileInputStream未找到带有 FileInputStream 的文件
【发布时间】:2015-09-01 07:42:58
【问题描述】:

我正在尝试检查我的程序是否正在扫描 File 的内容,但出现此错误:

Exception in thread "main" java.io.FileNotFoundException: input.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 lottery.main(lottery.java:40)

我没有在我的代码中看到问题,因为我总是以这种方式处理我的文件,似乎无法理解问题。

代码:

public static void main(String[] args) throws FileNotFoundException 
{
    Scanner in = new Scanner(System.in);
    System.out.println("Enter the name of the file with the ticket data.");
    String input = in.nextLine();
    File file = new File(input);

    in.close();

    Scanner scan = new Scanner(new FileInputStream(file));
    int lim = scan.nextInt();
    for(int i = 0; i < lim * 2; i++)
    {
        String name = scan.nextLine();
        String num = scan.nextLine();

        System.out.println("Name " + name);
    }

    scan.close();
}

【问题讨论】:

    标签: java file java.util.scanner filenotfoundexception fileinputstream


    【解决方案1】:

    A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.来自docs.oracle.com

    这意味着您的 FileInputStream 需要提供一个实际的文件系统文件。但是您只在调用 new File() 时创建了一个文件处理程序。所以你需要在调用file.createNewFile()的文件系统上创建文件;

    File file = new File(input); //here you make a filehandler - not a filesystem file.
    
    if(!file.exists()) {
        file.createNewFile(); // create your file on the file system
    } 
    
    Scanner scan = new Scanner(new FileInputStream(file)); // read from file system.
    

    【讨论】:

      【解决方案2】:

      检查是否从输入文件所在目录启动jvm。

      如果没有,则无法通过相对路径找到它。最终将其更改为绝对路径(类似于 /usr/me/input.txt)。

      如果文件位于您启动 java 程序的目录中,请检查文件的权限。启动 java 程序的用户可能看不到它。

      【讨论】:

        【解决方案3】:

        问题是您的程序在当前工作目录中找不到input.txt

        查看程序运行的目录并检查其中是否有一个名为input.txt 的文件。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-06-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-08-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多