การเขียนและอ่านข้อความในไฟล์
เมื่อสร้างไฟล์ได้แล้ว ขั้นตอนต่อไปคือการเพิ่มเนื้อหาจริงลงไป แบบฝึกหัดนี้จะให้เขียนข้อความสั้น ๆ ลงในไฟล์ข้อความ แล้วอ่านกลับมาเพื่อยืนยันว่าบันทึกสำเร็จ ซึ่งเป็นฟีเจอร์หลักของแอปพลิเคชันจดบันทึกทั่วไป
แพ็กเกจที่จำเป็นจาก java.io ได้ถูก import ไว้ให้แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Input/Output และ Streams ใน Java
คำแนะนำการฝึกหัด
- เขียนข้อความ
"Start from the beginning"ลงในไฟล์ชื่อ"note.txt" - สร้าง
FileWriterในโหมดappendสำหรับ"note.txt"โดยตั้งชื่อว่าfwAppendMode - เพิ่มข้อความ
" Add to the end"ลงในไฟล์โดยไม่ทับเนื้อหาเดิม - ใช้
FileReaderอ่านเนื้อหาในไฟล์และแสดงผลบน console ทีละหนึ่งตัวอักษร
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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());
}
}
}