การอ่านไฟล์ด้วย BufferedReader
เมื่องานดำเนินต่อไป บริษัทเริ่มได้รับไฟล์ข้อมูลตลาดขนาดใหญ่ขึ้นเรื่อย ๆ ผู้จัดการจึงแนะนำให้ใช้ Java I/O Streams เพื่อเพิ่มประสิทธิภาพการทำงาน ขั้นแรก ให้สร้างโซลูชันที่อ่านบรรทัดแรก ๆ ของไฟล์ CSV โดยใช้ character stream
คลาส BufferedReader และ FileReader ถูก import ให้เรียบร้อยแล้ว
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
การนำเข้าข้อมูลใน Java
คำแนะนำการฝึกหัด
- สร้าง reader โดยใช้ constructor แบบต่อกันโดยส่ง
filePathเข้าไปในFileReader - อ่านและแสดงผลบรรทัด header
- อ่านและแสดงผลแถวข้อมูลแรก
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
public class BufferedReaderExample {
public static void main(String[] args) {
String filePath = "sample_market_data.csv";
// Create a reader using chained constructors
try (BufferedReader reader = new BufferedReader(new ____(____))) {
// Read and print the header line
String header = ____.____();
System.out.println("Header: " + header);
// Read and print the first data row
String dataRow = reader.____();
System.out.println("First data row: " + ____);
System.out.println("Successfully read from file using BufferedReader");
} catch (IOException e) {
System.err.println("Error reading file: " + e.getMessage());
}
}
}