在前面學完了隨機數與例外處理之後,這篇要來學習Java中的檔案讀寫(File I/O)基礎,學會如何把資料寫入文字檔中,以及如何從文字檔中把資料讀取出來。
import java.io.FileWriter;
import java.io.IOException;
public class FileWriterDemo {
public static void main(String[] args) {
try {
// 建立 FileWriter 物件,參數為檔名
// 注意:如果檔案不存在,Java 會自動幫你建立;如果檔案已存在,預會直接覆蓋過去
FileWriter writer = new FileWriter("score.txt");
// 寫入文字內容
writer.write("Hello Java File I/O!\n");
writer.write("High Score: 9999\n");
// 關閉串流 (非常重要!確保資料確實寫入並釋放系統資源)
writer.close();
System.out.println("檔案寫入成功!");
} catch (IOException e) {
System.out.println("寫入檔案時發生錯誤:" + e.getMessage());
}
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
(2.)讀取範例程式碼
public class FileReaderDemo {
public static void main(String[] args) {
try {
// 指定要讀取的檔案
File file = new File("score.txt");
// 用 Scanner 讀取該檔案
Scanner scanner = new Scanner(file);
// 使用迴圈逐行讀取檔案內容
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println("讀取到的內容:" + line);
}
// 關閉 Scanner
scanner.close();
} catch (FileNotFoundException e) {
System.out.println("找不到指定的檔案:" + e.getMessage());
}
}
}