จัดการบันทึกขนาดยาวอย่างมีประสิทธิภาพ
เมื่อผู้ใช้เขียนบันทึกที่ยาวขึ้น ประสิทธิภาพในการประมวลผลก็มีความสำคัญมากขึ้น คลาส buffered ของ Java ช่วยให้อ่านและเขียนข้อความจำนวนมากได้อย่างมีประสิทธิภาพ ในแบบฝึกหัดนี้ จะได้ใช้ BufferedReader และ BufferedWriter เพื่อจัดการบันทึกที่บันทึกไว้ใน "note.txt"
ได้นำเข้าแพ็กเกจที่จำเป็นทั้งหมดจาก java.io ให้แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Input/Output และ Streams ใน Java
คำแนะนำการฝึกหัด
- สร้างอินสแตนซ์ของ
BufferedWriterชื่อbwโดยครอบFileWriterสำหรับไฟล์ชื่อ"note.txt" - เขียนข้อความบรรทัดแรก
"This is the first line"ลงในไฟล์ จากนั้นขึ้นบรรทัดใหม่โดยใช้เมธอด.newLine()แล้วเขียนข้อความบรรทัดที่สอง"This is the second line"ลงในไฟล์ - สร้างอินสแตนซ์ของ
BufferedReaderชื่อbrโดยครอบFileReaderเพื่ออ่านไฟล์"note.txt" - อ่านไฟล์ทีละบรรทัด
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
public class FileOperations {
public static void main(String[] args) {
try {
// Create a new instance of BufferedWriter
BufferedWriter bw = ____ ____(new FileWriter("note.txt"));
// Write the text, "This is the first line"
bw.____("This is the first line");
// Add a new line
bw.____();
// Write the second line of text, "This is the second line"
bw.____("This is the second line");
bw.close();
// Create a new instance of BufferedReader
BufferedReader br = ____ ____(new FileReader("note.txt"));
String line;
while ((line = br.____()) != null) {
System.out.println(line);
}
// Close the BufferedReader
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}