[英]Unable to read file with Scanner in Java
我正在尝试将File对象传递给Scanner构造函数。
File file = new File("in.txt");
try{
Scanner fileReader = new Scanner(file);
}
catch(Exception exp){
System.out.println(exp.getMessage());
}
我在项目,src和bin目录的根目录中有一个in.txt文件,以防我弄错位置。 我也尝试过给出绝对路径。 这条线
Scanner fileReader = new Scanner(file);
总是失败。 执行跳到main的结尾。 如果我拼错了文件名,则会得到FileNotFoundException。 我正在使用带有OpenJDK的Ubuntu 12.10 Java 1.7
如果您这样做: File file = new File("in.txt");
在你的java程序中
(假设它名为Program.java),则in.txt
文件应
在运行时位于程序的工作目录中。 所以如果你
像这样运行程序:
java Program
要么
java package1.package2.Program
并且您在运行此命令时位于/test1/test2/
,
那么in.txt
文件必须位于/test1/test2/
。
我在linux上运行,这是您需要做的
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Testing {
public static void main(String args[]) throws IOException {
Scanner s = null;
try {
//notice the path is fully qualified path
s = new Scanner(new File("/tmp/one.txt"));
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
}
结果如下:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.