CommencerCommencer gratuitement

Writing files with BufferedWriter

Now the analysis team has said they need to create summary files from their market data. Your task is to write a program that outputs a simple summary to a new file. This will be your first step in implementing file output operations for the data pipeline.

The BufferedWriter and FileWriter classes have been imported for you.

Cet exercice fait partie du cours

Importing Data in Java

Afficher le cours

Instructions

  • Create a writer using chained constructors.
  • Write the title line to the file.
  • Write two data lines to the file.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

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());
        }
    }
}
Modifier et exécuter le code