BufferWriter, writes to character based stream and BufferReader, reads from character based stream, so as to provide efficient writing/reading of characters, arrays, and strings.
BufferReader class:
BufferReader class reads text from a character based stream, read methods are as follows:
- public int read()
- public int read(char[] cbuf, int off, int len)
- public String readLine()
BufferWriter class:
BufferWriter writes text to a character based stream. Write methods are as follows:
- public void write(int c)
- public void write(char[] cbuf, int off, int len)
- public void write(String s, int off, int len)
We have discussed similar post to read & writer file in java:
- Java IO operation using BufferWriter & BufferReader (NIO).
- Java IO operations to read & write UTF contents using BufferReader/BufferWriter (without NIO).
- Read & write file contents (UTF) using InputStreamReader/OutputStreamWriter.
- Read & write contents (without UTF) using InputStreamReader/OutputStreamWriter
Program – Java file IO using BufferedReader & BufferedWriter
package org.learn.io;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class BufferReaderWriter {
public static void main(String[] args) throws IOException {
writeUsingBufferWriter();
readUsingBufferReader();
}
private static void writeUsingBufferWriter() throws IOException {
System.out.println("1. Start writing contents to file - BufferedWriter");
try (FileOutputStream fileStream = new FileOutputStream(new File("sampleFile.txt"));
OutputStreamWriter writer = new OutputStreamWriter(fileStream);
BufferedWriter bufferWriter = new BufferedWriter(writer)) {
bufferWriter.write("Soccer");
bufferWriter.newLine();
bufferWriter.write("Tennis");
bufferWriter.newLine();
bufferWriter.write("Badminton");
bufferWriter.newLine();
bufferWriter.write("Hockey");
bufferWriter.newLine();
}
System.out.println("2. Successfully written contents to file - BufferedWriter");
}
private static void readUsingBufferReader() throws IOException {
try (FileInputStream fileStream = new FileInputStream(new File("sampleFile.txt"));
InputStreamReader reader = new InputStreamReader(fileStream);
BufferedReader bufferedReader = new BufferedReader(reader)) {
System.out.println("\n3. Start Reading file using BufferedReader");
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
System.out.println("4. End Reading file using BufferedReader");
}
}
}
The content of sampleFile.txt is as follows:
Output – Java file IO using BufferedReader & BufferedWriter
1. Start writing contents to file - BufferedWriter 2. Successfully written contents to file - BufferedWriter 3. Start Reading file using BufferedReader Soccer Tennis Badminton Hockey 4. End Reading file using BufferedReader