Reading a file using FileReader and Scanner

雨燕双飞 提交于 2019-12-24 15:25:11

问题


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.

My code is:

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

Error is:

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

回答1:


You are encountering a compile time 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 { 
         //...
   }
}

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



来源:https://stackoverflow.com/questions/27756407/reading-a-file-using-filereader-and-scanner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!