[英]Reading a file in Java with Scanner
我正在嘗試獲取一個程序來讀取文本文件,但是即使我在項目目錄中設置了potato.txt文件,它也會引發FileNotFoundException。
import java.io.File;
import java.util.Scanner;
public static void main(String[] args) {
String potato = "potato.txt"; // assume this line can't be changed at all
Scanner scan = new Scanner(new File(potato)); // throws FileNotFoundException
while (scan.hasNextLine()) {
String line = scan.nextLine();
System.out.println(line);
}
}
}
嘗試使用完整路徑,如下所示:
File file = new File("C:/temp/potato.txt"); //This is just an example path, look up your files path and put it here.
Scanner scan = new Scanner(file);
另外,別忘了在完成后關閉掃描儀(在while
-loop之后):
scan.close();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.