Java FileWriter append() Method
Example
Add text with chained append() calls, and read it back:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.append("Hello").append(' ').append("World");
myWriter.close();
BufferedReader br = new BufferedReader(new FileReader("filename.txt"));
System.out.println(br.readLine());
br.close();
}
}
Definition and Usage
The append() method adds a character or text to the writer. The text can be any CharSequence (a sequence of characters), like a String or a StringBuilder.
It works like write(), but it returns the writer itself. This lets you chain calls, like myWriter.append("Hello").append(' ').
Note: append() does not keep the old content of the file. To add text to the end of an existing file, open it in append mode: new FileWriter("filename.txt", true).
Syntax
One of the following:
public Writer append(char c)
public Writer append(CharSequence csq)
public Writer append(CharSequence csq, int start, int end)
Parameter Values
| Parameter | Description |
|---|---|
| c | Optional. The character to add. |
| csq | Optional. The text to add, for example a String or a StringBuilder. If it is null, the text null is added. |
| start | Optional. The index of the first character to take from csq. |
| end | Optional. The index after the last character to take from csq. |
Technical Details
| Returns: | The same writer, so you can chain more calls. |
|---|---|
| Throws: | IndexOutOfBoundsException - if start or end is outside the text, or start is bigger than end. |
Related Pages
❮ FileWriter Methods