流的链式使用
您的公司有多种文本编码的 数据文件。为统一处理流程,经理要求您实现一个显式处理 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());
}
}
}