Java 使用FileReader和Scanner读取文件

Java 使用FileReader和Scanner读取文件,java,file,java.util.scanner,Java,File,Java.util.scanner,我是Java初学者,读过类似的问题,但仍然不明白为什么我的代码会显示FileNotFound异常。 我的文件在同一个目录中 我的代码是: import java.io.*; import java.util.Scanner; public class reader { public static void main(String[] args) { Scanner in = new Scanner(System.in); int x = in.next

我是Java初学者,读过类似的问题,但仍然不明白为什么我的代码会显示FileNotFound异常。 我的文件在同一个目录中

我的代码是:

import java.io.*;
import java.util.Scanner;

public class reader {
    public static void main(String[] args) { 
        Scanner in = new Scanner(System.in);
        int x = in.nextInt();
        double y = in.nextDouble();
        float g = in.nextFloat();
        String a = in.next();
        File file = new File("v.txt");
        System.out.println(x + "" + y + "" + g + "" + a); 
        Scanner inFile = new Scanner(new FileReader(file));
        String u = inFile.nextLine();
        System.out.println(file.getAbsolutePath());
        System.out.println(u);
    }
}
错误是:

17: error: unreported exception FileNotFoundException; must be caught or declared to be thrown
     Scanner inFile = new Scanner(new FileReader(file));
                                  ^
1 error

您遇到编译时错误:

error: unreported exception FileNotFoundException; must be caught or declared to be thrown
 Scanner inFile = new Scanner(new FileReader(file));
这是一种简单的修复方法:

public class reader {
   public static void main(String[] args) throws Exception { 
         //...
   }
}

尽管使用try{…}catch(…){}是处理可能的运行时异常的更好方法。

您遇到了编译时错误:

error: unreported exception FileNotFoundException; must be caught or declared to be thrown
 Scanner inFile = new Scanner(new FileReader(file));
这是一种简单的修复方法:

public class reader {
   public static void main(String[] args) throws Exception { 
         //...
   }
}

尽管使用try{…}catch(…){}是处理可能的运行时异常的更好方法。

从运行代码的同一目录?是否从IDE运行代码,如果是,是哪个IDE?@AniketThakur是的。my.java文件和.txt文件都在同一个文件夹中。此外,在对文件对象执行读/写操作之前,您可能希望对文件对象使用tp
exists()
。@edbale您搜索了其他内容。如果在运行时找不到文件,将抛出
FileNotFoundException
。您的错误由编译器触发,因为您的代码错误(未处理的异常)。这是不同的,这就是为什么我问您是否搜索了错误消息。您运行代码的目录是同一个目录?您是否从IDE运行代码,如果是,是哪个IDE?@Anikethakur是的。my.java文件和.txt文件都在同一个文件夹中。此外,在对文件对象执行读/写操作之前,您可能希望对文件对象使用tp
exists()
。@edbale您搜索了其他内容。如果在运行时找不到文件,将抛出
FileNotFoundException
。您的错误由编译器触发,因为您的代码错误(未处理的异常)。这是不一样的,这就是为什么我问你是否搜索了错误消息。是的,它工作了,但是如果我知道我的文件存在,为什么我需要放这个?每次访问文件时都需要它吗?这也是可能的。@edbale你知道,但编译器不知道你知道-他也不会相信你或任何读或写这句话的人;-)@edbale“但是如果我知道我的文件存在,为什么我需要放这个?”你确定你的文件会一直存在吗?从物理上来说是不可能删除它的吗?@laune谢谢你的帮助。是的,它起作用了,但是如果我知道我的文件存在,为什么我需要把它放在这里?每次访问文件时都需要它吗?这也是可能的。@edbale你知道,但编译器不知道你知道-他也不会相信你或任何读或写这句话的人;-)@edbale“但是如果我知道我的文件存在,为什么我需要放这个?”你确定你的文件会一直存在吗?“从物理上来说,删除它是不可能的吗?”劳恩,谢谢你的帮助。