Append Text to an Existing File in Java

Exercise:

Write a Java Program to append text to an existing file.

Click Here to View the Solution!
 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) {
        }
    }
} 
Click Here to View the Output!
When you run the program, the test.txt file now contains:
This is a Test file.Added text
Click Here to View the Explanation!
  • In this program, for retrieving the current directory location, a System property namely user.dir property is utilized. The location is then stored in a variable called path.
  • Similarly, the variable text is used for storing the input text which has to be appended .
  • Next, this text is appended to the existing file using File class’ write method inside the try-catch block.
  • There are three arguments passed to the write() method. One is the file path, second is the input text which is to be added, and third is the mode in which the file is to be opened for writing. In this case, our mode is APPEND.
  • There is a probability of IOException to arise in relation to the write() method for which exception handling must be incorporated in the try-catch block.