[英]FileReader/Scanner reading file name rather than contents of .txt file
[英]Reading a file using FileReader and Scanner
我是Java初学者,曾经阅读过类似的问题,但是仍然不明白为什么我的代码显示FileNotFound Exception。 我的文件在同一目录中。
我的代码是:
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(...){}是处理可能的运行时异常的更好方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.