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.
This exercise is part of the course
Importing Data in Java
Exercise instructions
- Create a writer using chained constructors.
- Write the title line to the file.
- Write two data lines to the file.
Hands-on interactive exercise
Have a go at this exercise by completing this sample 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());
}
}
}