Algorithm


  1. Open File:

    • Create a File object with the path to the existing file.
    • Use a FileWriter or BufferedWriter to open the file in append mode. This ensures that new content will be added to the end of the file.
  2. Write Text:

    • Create a String or use the text you want to append to the file.
  3. Append Text:

    • Use the write method of the FileWriter or BufferedWriter to append the text to the file.
  4. Close File:

    • Close the FileWriter or BufferedWriter to ensure that changes are flushed and resources are released.

 

Code Examples

#1 Code Example- Java Programing Append text to existing file

Code - Java Programming

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class AppendFile {

    public static void main(String[] args) {

        String path = System.getProperty("user.dir") + "\\src\\test.txt";
        String text = "Added text";

        try {
            Files.write(Paths.get(path), text.getBytes(), StandardOpenOption.APPEND);
        } catch (IOException e) {
        }
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
This is a
Test file.Added text

#2 Code Example- Java Programing Append text to an existing file using FileWriter

Code - Java Programming

import java.io.FileWriter;
import java.io.IOException;

public class AppendFile {

    public static void main(String[] args) {

        String path = System.getProperty("user.dir") + "\\src\\test.txt";
        String text = "Added text";

        try {
            FileWriter fw = new FileWriter(path, true);
            fw.write(text);
            fw.close();
        }
        catch(IOException e) {
        }
    }
}
Copy The Code & Try With Live Editor

Output

x
+
cmd
This is a
Test file.Added text
Advertisements

Demonstration


Java Programing Example to Append Text to an Existing File-DevsEnv