Thursday, June 26, 2025

File I/O

We have seen Scanner used to quickly gather one line, for example, to turn "Hello World" into a personalized "Hello, Andre" or something similar. But there are better ways to handle reading and writing much larger amounts of text: whole files.

BufferedReader and BufferedWriter are commonly used in Java to efficiently read from and write to text files. BufferedReader reads text from a file line by line, which is useful for processing large files without loading the entire contents into memory at once. For example, to read every line from a file and print it to the console, you can use:

BufferedReader reader = new BufferedReader(new FileReader("input.txt"));

String line;

while ((line = reader.readLine()) != null) {

    System.out.println(line);

}

reader.close();

This code opens "input.txt", reads each line until the end of the file, prints each line, and then closes the reader to free resources.

BufferedWriter is used for writing text to files efficiently. It buffers the output, so writing many small pieces of data is faster. For example, to write a couple of lines to a file:

BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));

writer.write("This is the first line.");

writer.newLine();

writer.write("This is the second line.");

writer.close();

This code creates or overwrites "output.txt", writes two lines, and closes the writer when done.

If you want to copy the contents of one file to another, you can combine both classes:

BufferedReader reader = new BufferedReader(new FileReader("input.txt"));

BufferedWriter writer = new BufferedWriter(new FileWriter("output.txt"));

String line;

while ((line = reader.readLine()) != null) {

    writer.write(line);

    writer.newLine();

}

reader.close();

writer.close();

This reads each line from "input.txt" and writes it to "output.txt", preserving the line structure.

Always remember to close both the reader and writer after use, as this ensures all data is properly written and resources are released. BufferedReader and BufferedWriter are the preferred way to handle text files in Java when you need efficiency and simplicity.

No comments:

Post a Comment

Switch

 Other than if/if-else/if-else if-else and the ternary operator, there is yet another common and important conditional expression in Java th...