java - 使用 FileReader 和 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.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(...){ } 是处理可能的运行时异常的更好方法。

关于java - 使用 FileReader 和 Scanner 读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27756407/

相关文章:

java - Eclipse 建议更改代码。我必须如何以及在何处实例化导入类的对象?

java - Hazelcast 主题 - 消息似乎仅由一名成员发送

java - 当相机平移时, Sprite 不会跟随 box2d 主体,但如果相机在 libgdx 中是静态的,则效果良好

java - 窗口打开时出错?

java - 更改现有 JDialog 的模式

file - 禁用 Sublime Text 文件重新加载对话框

arrays - 从文件中读取字符串并转换为数组 Julia

c++ - 在 C++ 中获取文本文件的第 n 行

java - 如何在 Java 的 Scanner 实用程序中将输入放在下一行

java - 使用 Scanner 时检查变量类型