串接串流(Stream chaining)
你們公司有多個以不同文字編碼儲存的資料檔。為了讓處理流程一致,主管要你實作一個能明確以 UTF-8 編碼讀取的檔案讀取器。這需要把多個串流串接起來——這是 Java I/O 的關鍵概念。
本題已為你匯入 BufferedReader、InputStreamReader、FileInputStream 和 StandardCharsets 類別。
本練習屬於課程
Java 中的資料匯入
練習說明
- 將
BufferedReader串接到InputStreamReader,再串接到FileInputStream。 - 讀取並印出檔案的第一行。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
public class StreamChainingExample {
public static void main(String[] args) {
String filePath = "sample_market_data.csv";
// Chain three stream classes together
try (
BufferedReader reader = new ____(
new ____(
new ____(filePath),
StandardCharsets.UTF_8
)
)
) {
// Read and print the first line
String firstLine = reader.____();
System.out.println("First line (UTF-8): " + ____);
System.out.println("Successfully read using chained streams");
} catch (IOException e) {
System.err.println("Error: " + e.getMessage());
}
}
}