In this tutorial, we aim to understand the use of BufferedReader and BufferedWriter classes in Java.
After this tutorial, you will be able to use BufferedReader for reading text from a character-input stream and BufferedWriter for writing text to a character-output stream.
Basic understanding of Java programming and I/O Streams in Java is required.
BufferedReader
is a class in Java that reads text from an input-stream (like a file) buffering characters so as to provide efficient reading of characters, arrays, and lines. The buffer size may be specified, but by default it's large enough for most purposes.
Example:
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
BufferedWriter
is a class in Java that writes text to an output-stream (like a file) buffering characters so as to provide efficient writing of single characters, arrays, and strings.
Example:
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
import java.io.*;
public class ReadFile {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
String line = null;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
In this example, we read each line from a file named "input.txt" and print it on the console. The readLine()
method returns null when the end of the file is reached.
import java.io.*;
public class WriteFile {
public static void main(String[] args) throws IOException {
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
writer.write("This is a test line.");
writer.newLine();
writer.write("This is another test line.");
writer.close();
}
}
In this example, we write two lines into a file named "output.txt". The newLine()
method is used to insert a newline.
In this tutorial, we have learned about reading from and writing to text files using BufferedReader and BufferedWriter in Java. We have seen how to iterate over each line in a file with BufferedReader and how to write lines to a file with BufferedWriter.
Write a Java program that reads a text file and prints the number of lines in the file.
Write a Java program that reads a text file and writes the contents into a new file.
import java.io.*;
public class LineCount {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
int lines = 0;
while (reader.readLine() != null) lines++;
reader.close();
System.out.println("Number of lines: " + lines);
}
}
import java.io.*;
public class FileCopy {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));
String line = null;
while((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
reader.close();
writer.close();
}
}