寫入並讀取備忘錄
既然你已經會建立檔案,接下來就來加入實際內容。你會把一段短訊息寫入文字檔,然後再讀出來確認是否正確儲存。這是任何記事應用程式的核心功能。
已為你匯入 java.io 所需的所有套件。
本練習屬於課程
Java 的輸入/輸出與串流
練習說明
- 將文字
"Start from the beginning"寫入名為"note.txt"的檔案。 - 以
append模式為"note.txt"建立FileWriter,命名為fwAppendMode。 - 將文字
" Add to the end"附加到檔案中,而不要覆寫原有內容。 - 使用
FileReader讀取檔案內容,並在主控台一次顯示一個字元。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
class FileReadWrite {
public static void main(String[] args) {
try {
FileWriter fw = new FileWriter("note.txt");
// Write "Start from the beginning" to the file
fw.____("Start from the beginning");
fw.close();
// Create a FileWriter in append mode
FileWriter fwAppendMode = new ____("note.txt", ____);
// Add " Add to the end" to the end of file
fwAppendMode.____(" Add to the end");
fwAppendMode.close();
FileReader fr = new FileReader("note.txt");
int character;
// Read the file content character by character
while ((character = fr.____()) != -1) {
System.out.print((char) character);
}
fr.close();
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}