共計 530 個字符,預計需要花費 2 分鐘才能閱讀完成。
要讀取一個 txt 文件中的內容,可以使用 Java 中的 File 類和 Scanner 類。下面是一個簡單的示例代碼:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile {public static void main(String[] args) {try {File file = new File("file.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();} catch (FileNotFoundException e) {System.err.println(" 文件未找到 ");
}
}
}
在上面的代碼中,首先創建一個 File 對象來表示要讀取的 txt 文件,然后創建一個 Scanner 對象來讀取文件內容。使用 while 循環來逐行讀取文件內容,并打印出來。最后別忘了關閉 Scanner 對象。
丸趣 TV 網 – 提供最優質的資源集合!
正文完