CodeGym/Java Blog/Java IO & NIO/BufferedReader and BufferedWriter
Author
John Selawsky
Senior Java Developer and Tutor at LearningTree

BufferedReader and BufferedWriter

Published in the Java IO & NIO group
members
BufferedReader and BufferedWriter - 1Java’s BufferedReader class reads text from a stream of symbols, buffering the symbols to efficiently read characters, arrays, and strings. You can pass the buffer size to the constructor as a second argument. BufferedReader and BufferedWriter - 2Constructors:
BufferedReader(Reader in) // Creates a buffered stream for reading symbols. It uses the default buffer size.
BufferedReader(Reader in, int sz) // Creates a buffered stream for reading symbols. It uses the specified buffer size.
Methods:
close() // Close the stream
mark(int readAheadLimit) // Mark the position in the stream
markSupported() // Indicates whether stream marking is supported
int	read() // Read the buffer
int	read(char[] cbuf, int off, int len) // Read the buffer
String	readLine() // Next line
boolean	ready() // Is the stream ready to read?
reset() // Reset the stream
skip(long n) // Skip characters

Here's an example of using the BufferedReader and BufferedWriter classes:

Reading a file:
import java.io.*;

public class ReadFile {
	public static void main(String[] args) {
		try {
			File file = new File("file.txt");
			FileReader fileReader = new FileReader(file); // A stream that connects to the text file
			BufferedReader bufferedReader = new BufferedReader(fileReader); // Connect the FileReader to the BufferedReader

			String line;
			while((line = bufferedReader.readLine()) != null) {
				System.out.println(line); // Display the file's contents on the screen, one line at a time
			}

			bufferedReader.close(); // Close the stream
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Java's BufferedWriter class writes text to an output character stream, buffering the characters in order to efficiently write characters, arrays, and strings. You can pass the buffer size to the constructor as a second argument. Constructors:
BufferedWriter(Writer out) // Create a buffered output character stream that uses the default buffer size.
BufferedWriter(Writer out, int sz) // Creates a buffered character output stream that uses a buffer with the specified size.
Methods:
close() // Close the stream
flush() // Send the data from the buffer to the Writer
newLine() // Move to a new line
write(char[] cbuf, int off, int len) // Write to the buffer
write(int c) // Write to the buffer
write(String s, int off, int len) // Write to the buffer

Here's an example of using Java's BufferedReader and BufferedWriter classes:

Writing to a file:
import java.io.*;

public class WriteFile {
    public static void main(String[] args) {
        String[] list = {"one", "two", "three", "fo"};
        try {
            File file = new File("file.txt");
            FileWriter fileReader = new FileWriter(file); // A stream that connects to the text file
            BufferedWriter bufferedWriter = new BufferedWriter(fileReader); // Connect the FileWriter to the BufferedWriter

            for (String s : list) {
                bufferedWriter.write(s + "\n");
            }

            bufferedWriter.close (); // Close the stream
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
FileWriter immediately writes data to disk. Every time we access it, the buffer wrapped around it speeds up our application. The buffer will write data internally, and then later write large chunks of files to disk. We read data from the console and write it to a file:
import java.io.*;

class ConsoleRead {
    public static void main(String[] args) {
        try {
            File file = new File("file.txt");
            InputStreamReader inputStreamReader = new InputStreamReader(System.in); // A stream for reading from the console
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader); // Connect InputStreamReader to a BufferedReader

            FileWriter fileReader = new FileWriter(file); // A stream that connects to the text file
            BufferedWriter bufferedWriter = new BufferedWriter(fileReader); // Connect the FileWriter to the BufferedWriter

            String line;
            while(!(line = bufferedReader.readLine()).equals("exit")) {
                bufferedWriter.write(line);
            }

            bufferedReader.close(); // Close the stream
            bufferedWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Comments (1)
  • Popular
  • New
  • Old
You must be signed in to leave a comment
Branka
Level 41 , Belgrade, Serbia
8 March 2020, 09:08
I am very thankful for this article. I had some problems understanding this topic and these examples made it more clear.