Java Exercises: Write and read a plain text file

Java Input-Output: Exercise-15 with Solution

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

Sample Solution:

Java 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 Eexercise15 {
     public static void main(String a[]){
        StringBuilder sb = new StringBuilder();
        String strLine = "";
             String filename= "/home/students/myfile.txt";
             FileWriter fw = new FileWriter(filename,false); 
             //appends the string to the file
             fw.write("Python Exercises\n");
             BufferedReader br = new BufferedReader(new FileReader("/home/students/myfile.txt"));
             //read the file content
             while (strLine != null)
                strLine = br.readLine();
           catch(IOException ioe)
            System.err.println("IOException: " + ioe.getMessage());

Sample Output:

Python Exercises                                                                                              

Flowchart :

Flowchart: Write and read a plain text file

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to store text file content line by line into an array.
Next: Write a Java program to append text to an existing file.

What is the difficulty level of this exercise?

Inviting useful, relevant, well-written and unique guest posts