使用FileReader和Scanner读取文件 [英] Reading a file using FileReader and Scanner

查看:90
本文介绍了使用FileReader和Scanner读取文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java初学者,曾经阅读过类似的问题,但仍然不明白为什么我的代码显示FileNotFound Exception. 我的文件在同一目录中.

I am a Java beginner and have read similar questions but still I dont get why my code is showing a FileNotFound Exception. My file is in the same directory.

我的代码是:

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));

这是修复它的简单方法:

This is a simple way of fixing it:

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

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

although using try {...} catch(...){ } is a better way of dealing with the possible run time exception.

这篇关于使用FileReader和Scanner读取文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆