Java 读取文件
读取文件
在上一章中,您学习了如何创建和写入文件。
在下面的实例中,我们使用 Scanner 类来读取在上一章中创建的文本文件的内容:
实例
import java.io.File; // Import the File classimport java.io.FileNotFoundException; // Import this class to handle errorsimport java.util.Scanner; // Import the Scanner class to read text filespublic class ReadFile {public static void main(String[] args) {try {File myObj = new File("filename.txt");Scanner myReader = new Scanner(myObj);while (myReader.hasNextLine()) {String data = myReader.nextLine();System.out.println(data);}myReader.close();} catch (FileNotFoundException e) {System.out.println("An error occurred.");e.printStackTrace();}}}
输出应为:
Files in Java might be tricky, but it is fun enough!
获取文件信息
要获取有关文件的更多信息,请使用 File 方法:
实例
import java.io.File; // Import the File classpublic class GetFileInfo { public static void main(String[] args) {File myObj = new File("filename.txt");if (myObj.exists()) {System.out.println("File name: " + myObj.getName());System.out.println("Absolute path: " + myObj.getAbsolutePath());System.out.println("Writeable: " + myObj.canWrite());System.out.println("Readable " + myObj.canRead());System.out.println("File size in bytes " + myObj.length());} else {System.out.println("The file does not exist.");}}}
输出应为:
File name: filename.txt
Absolute path: C:\Users\MyName\filename.txt
Writeable: true
Readable: true
File size in bytes: 0
Absolute path: C:\Users\MyName\filename.txt
Writeable: true
Readable: true
File size in bytes: 0
注意:Java API 中有许多可用类可用于在 Java 中读取和写入文件:
FileReader、BufferedReader、files、Scanner、FileInputStream、FileWriter、BufferedWriter、FileOutputStream 等。使用哪个类取决于您使用的 Java 版本,以及是否需要读取字节或字符,以及文件/行的大小等。提示: 要删除文件,请学习本站 Java 删除文件 章节。