開始使用免費開始

使用 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());
        }
    }
}
編輯並執行程式碼