This class BufferWriter buffers stream outputs. For this purpose, it contains an internal buffer in which the outputs of write are temporarily stored. Once the buffer is full, all buffered output is written to the real stream. The same happens when the flush method is called.
Since the output of write is cached, and thus the write calls to the real stream are reduced, performance is increased. Using the BufferdWriter class is useful whenever output is to be written to a file.
import java.io.FileWriter;
import java.io.BufferedWriter;
FileWriter <fw_name> = new FileWriter("<file_name.txt>");
BufferedWriter <bw_name> = new BufferedWriter(<fw_name>);
import java.io.IOException;
import java.io.FileWriter;
import java.io.BufferedWriter;
public class BufferedWriting {
public static void main(String[] args) throws IOException {
FileWriter fw;
BufferedWriter bw;
try {
fw = new FileWriter("myFile.txt");
bw = new BufferedWriter(fw);
bw.write("Lorem ");
bw.write("Ipsum ");
bw.write("Dolor ");
bw.write("Sit\n");
bw.append("Amet");
bw.close();
}
catch (IOException e){
System.out.println("Error while writing the file: myFile.txt");
System.out.println(e.toString());
}
}
}
[myFile.txt]
Lorem Ipsum Dolor Sit
Amet