开始使用免费开始使用

使用 BufferedWriter 写入文件

现在,分析团队表示需要从其市场数据中生成摘要文件。您的任务是编写一个程序,将简单的摘要输出到一个新文件中。这将是您在数据管道中实现文件输出操作的第一步。

BufferedWriterFileWriter 类已为您导入。

本练习是课程的一部分

Java 中的数据导入

查看课程

练习说明

  • 使用链式构造函数创建一个 writer。
  • 将标题行写入文件。
  • 再写入两行数据。

交互式实操练习

通过完成这段示例代码来试试这个练习。

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());
        }
    }
}
编辑并运行代码