[英]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.