การเขียนไฟล์ด้วย BufferedWriter
ตอนนี้ทีมวิเคราะห์ข้อมูลต้องการสร้างไฟล์สรุปจากข้อมูลตลาด งานของคุณคือเขียนโปรแกรมที่บันทึกข้อมูลสรุปอย่างง่ายลงในไฟล์ใหม่ นี่จะเป็นก้าวแรกในการนำการดำเนินการเอาต์พุตไฟล์ไปใช้ในไปป์ไลน์ข้อมูล
คลาส BufferedWriter และ FileWriter ได้รับการนำเข้าให้แล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การนำเข้าข้อมูลใน Java
คำแนะนำการฝึกหัด
- สร้าง writer โดยใช้ constructor แบบต่อกัน
- เขียนบรรทัดหัวเรื่องลงในไฟล์
- เขียนข้อมูลสองบรรทัดลงในไฟล์
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
public class BufferedWriterExample {
public static void main(String[] args) {
String filePath = "summary.txt";
// Create a writer using chained constructors
try (BufferedWriter writer = new ____(new FileWriter(filePath))) {
// Write the title line
____.____("MARKET DATA SUMMARY");
writer.newLine();
// Write two data lines
writer.____("Total Records: 156");
writer.newLine();
writer.____("Date Range: 2023-01-01 to 2023-06-30");
writer.newLine();
System.out.println("Summary file created successfully");
} catch (IOException e) {
System.err.println("Error writing file: " + e.getMessage());
}
}
}