w3resource

Java: Append text to an existing file


16. Append Text to File

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

Sample Output:

Python Exercises                                                                                              
Java Exercises                                                                                                
null

Flowchart:

Flowchart: Append text to an existing file


For more Practice: Solve these Related Problems:

  • Write a Java program to append a new line of text to an existing file using FileWriter in append mode.
  • Write a Java program to add text to the end of a file without overwriting its current content.
  • Write a Java program to append user-provided text to a file and then display the updated file content.
  • Write a Java program to repeatedly append lines to a file and then count the total number of lines present.

Go to:


PREV : Write and Read Text File.
NEXT : Read First 3 Lines of File.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.