Write a Java program to write and read a plain text file


This Java program demonstrates how to write to and read from a file using the FileWriter and BufferedReader classes. The program first creates a new StringBuilder object and initializes an empty string line.

It then tries to write a string "Python Exercises" to a file named "file.txt" using the FileWriter class with the false parameter, which means the file will be overwritten if it already exists. If the writing process fails, the program will catch and handle the IOException by printing an error message.

Next, the program opens the same file using the BufferedReader class with the FileReader class as its argument. It then reads the contents of the file line by line and appends each line to the StringBuilder object using the append() method. Additionally, it adds a line separator using the System.lineSeparator() method to make the output readable.

Finally, the program prints each line of the file to the console using the System.out.println() method. Note that the BufferedReader class reads the first line of the file before the loop, which is why the program does not print the first line. Also, the System.out.println(line) statement inside the loop should be moved before the line = reader.readLine() statement to print the first line.

Source Code

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
public class WriteRead
{
	public static void main(String a[])
	{
		StringBuilder builder = new StringBuilder();
		String line = "";
		try
		{
			String filename= "file.txt";
			FileWriter fw = new FileWriter(filename,false);
			//appends the string to the file
			fw.write("Python Exercises");
			fw.close();
			BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
			//read the file content
			while (line != null)
			{
				builder.append(line);
				builder.append(System.lineSeparator());
				line = reader.readLine();
				System.out.println(line);
			}
			reader.close();
		}
		catch(IOException ioe)
		{
			System.err.println("IOException : " + ioe.getMessage());
		}
	}
}

Output

Python Exercises
null