English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java flow control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Java other topics

Java program appends text to an existing file

Comprehensive Java Examples

In this program, you will learn various techniques to append Java text to existing files.

Before appending text to an existing file, we assume that insrcThere is a folder namedtest.txtfile.

This istest.txtcontent

This is a
Test file.

Example1:Append text to an existing file

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) {
        }
    }
}

When running the program,test.txtThe file now contains:

This is a
Test file.Added text

In the above program, we use the System.user.dir attribute to get the current directory path stored in the variable. CheckJava program to get the current directory to getMore information.

Similarly, the text to be added is also stored in the variable text. Then, in a try-In the catch block, we use the Files.write() method to append text to the existing file.

The write() method takes the path of the given file, the text to be written to the file, and how to open the file for writing. In our example, we use the APPEND option for writing

Since the write() method may return IOException, we use a try-catch block to correctly catch exceptions.

Example2:Use FileWriter to append text to an existing file

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) {
        }
    }
}

The output of the program is as follows1Same.

In the above program, we use an instance (object) of FileWriter instead of the write() method to append text to an existing file

When creating the FileWriter object, we pass the file path and true as the second parameter. True indicates that we allow the file to be appended

Then, we use the write() method to append the given text and close the file writer

Comprehensive Java Examples