[英]scanner class in java
嘿,我正在嘗試編譯以下代碼,以基本上從文件中讀取內容,但是它無法正常工作。 它在第4行給了我一個java.io.FILENOTFOUNDEXCEPTION錯誤。 幫助將不勝感激。
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) {
File fin = new File ("matrix1.txt");
Scanner scanner = new Scanner(fin);
while (scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
}
}
}
嘗試將絕對路徑放入文件,例如
c:\\\\java\\\\matrix1.txt
或/home/user/java/matrix1.txt
===哎呀
您需要捕獲正在拋出的異常。 這里有幾個選擇:
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) throws FileNotFoundException {
File fin = new File ("matrix1.txt");
Scanner scanner = new Scanner(fin);
while (scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
}
}
}
要么
import java.io.*;
import java.util.*;
public class test{
public static void main(String args[]) {
File fin = new File ("matrix1.txt");
Scanner sc = null;
try {
scanner = new Scanner(fin);
}
catch(FileNotFoundException e) {
System.out.println("File does not exist...");
return;
}
while (scanner.hasNextLine()){
String line = scanner.nextLine();
System.out.println(line);
}
}
}
如果使用Eclipse,請確保matrix1.txt位於src文件夾中。
如果您使用的是NetBeans / Eclipse之類的IDE,則需要將要讀取的文件放在項目文件夾中。 這通常比src文件夾高1級。
萬一找不到文件夾,一個不錯的選擇是嘗試創建一個文件。 這樣,您就知道文件的創建位置,並且可以將要讀取的文件放在同一文件夾中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.