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 刪除檔案 章。