Java 读取文件
读取文件
在上一章中,你学习了如何创建和写入文件。
在下面的示例中,我们使用 Scanner
类来读取我们在上一章中创建的文本文件的内容
示例
import java.io.File; // Import the File class
import java.io.FileNotFoundException; // Import this class to handle errors
import java.util.Scanner; // Import the Scanner class to read text files
public 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();
}
}
}
输出将是:
Java 中的文件操作可能有点棘手,但足够有趣!
获取文件信息
要获取有关文件的更多信息,可以使用 File
类的任何方法
示例
import java.io.File; // Import the File class
public 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.");
}
}
}
输出将是:
文件名:filename.txt
绝对路径:C:\Users\MyName\filename.txt
可写入:true
可读取:true
文件大小(字节):0
注意: Java API 中有许多可用的类可以用于在 Java 中读写文件:FileReader、BufferedReader、Files、Scanner、FileInputStream、FileWriter、BufferedWriter、FileOutputStream
等。使用哪一个取决于您使用的 Java 版本、是否需要读取字节或字符以及文件/行的大小等。
提示:要删除文件,请阅读我们的 Java 删除文件 章。