🌐
Tutorialspoint
tutorialspoint.com › java › lang › stringbuilder_append_string.htm
Java.lang.StringBuilder.append() Method
The following example shows the usage of java.lang.StringBuilder.append() method. package com.tutorialspoint; import java.lang.*; public class StringBuilderDemo { public static void main(String[] args) { StringBuilder str = new StringBuilder("tutorials "); System.out.println("string = " + str); // appends the string argument to the StringBuilder str.append("point"); // print the StringBuilder after appending System.out.println("After append = " + str); str = new StringBuilder("1234 "); System.out.println("string = " + str); // appends the string argument to the StringBuilder str.append("!#$%"); // print the StringBuilder after appending System.out.println("After append = " + str); } } Let us compile and run the above program, this will produce the following result − ·
🌐
Educative
educative.io › answers › how-to-append-to-an-array-in-java
How to append to an array in Java
Steps to append an element using Arrays.copyOf(): Create a new larger array: The new array should have a size greater than the original one by 1. Copy over the content: Use Arrays.copyOf() to copy all elements of the original array into the new one. Insert the new element: Add the new element to the last position of the new array. import java.util.Arrays; class ArrayAppend { public static void main( String args[] ) { int[] arr = { 10, 20, 30 }; System.out.println(Arrays.toString(arr)); arr = Arrays.copyOf(arr, arr.length + 1); arr[arr.length - 1] = 40; // Assign 40 to the last element ·
🌐
GeeksforGeeks
geeksforgeeks.org › java › stringbuffer-append-method-in-java-with-examples
StringBuffer append() Method in Java with Examples - GeeksforGeeks
July 11, 2025 - // Java program to illustrate the // StringBuffer append(boolean a) import java.lang.*; public class Geeks { public static void main(String[] args) { StringBuffer sbf1 = new StringBuffer("We are geeks and its really "); System.out.println("Input: " + sbf1); // Appending the boolean value sbf1.append(true); System.out.println("Output: " + sbf1); System.out.println(); StringBuffer sbf2 = new StringBuffer("We are lost - "); System.out.println("Input: " + sbf2); // Appending the boolean value sbf2.append(false); System.out.println("Output: " + sbf2); } } Output: Input: We are geeks and its really Output: We are geeks and its really true Input: We are lost - Output: We are lost - false ·
🌐
Codecademy
codecademy.com › docs › java › stringbuilder › .append()
Java | StringBuilder | .append() | Codecademy
August 22, 2022 - The following example creates a StringBuilder with a specified String and then uses the .append() method to change it: import java.util.*; public class Example { public static void main(String[] args) { StringBuilder str = new StringBuilder("Hello"); System.out.println(str.toString()); str.append(" World!"); System.out.println(str.toString()); } } Copy to clipboard ·
🌐
ZetCode
zetcode.com › java › appendfile
Java append to file - learn how to append to file in Java
The java.nio.file.Files class is a convenient class to easily append data to a file. ... import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; void main() throws IOException { String fileName = "src/main/resources/towns.txt"; String town = "Žilina\n"; Files.writeString(Paths.get(fileName), town, StandardCharsets.UTF_8, StandardOpenOption.APPEND); }
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-program-to-append-a-string-in-an-existing-file
Java Program to Append a String in an Existing File - GeeksforGeeks
July 11, 2025 - // Java Program to Append a String to the // End of a File // Importing input output classes import java.io.*; // Main class class GeeksforGeeks { // Method 1 // TO append string into a file public static void appendStrToFile(String fileName, String str) { // Try block to check for exceptions try { // Open given file in append mode by creating an // object of BufferedWriter class BufferedWriter out = new BufferedWriter( new FileWriter(fileName, true)); // Writing on output stream out.write(str); // Closing the connection out.close(); } // Catch block to handle the exceptions catch (IOException
🌐
Edureka
edureka.co › blog › append-method-in-java
append() Method in Java: StringBuffer vs StringBuilder Example | Edureka
October 23, 2019 - Now that you are aware of the general syntax, let’s check out different ways/forms in which the method append in Java can be used. Different ways to represent the append method are: ... Now that you are aware of the concept, let’s try to understand the concept with the help of an example. Below given code shows you the usage of StringBuilder class. Have a look! ... import java.util.*; import java.util.concurrent.LinkedBlockingQueue; public class A { public static void main(String[] argv) throws Exception { StringBuilder str = new StringBuilder(); str.append("ABC"); System.out.println("Stri
🌐
Vultr Docs
docs.vultr.com › java › examples › append-text-to-an-existing-file
Java Program to Append Text to an Existing File | Vultr Docs
December 9, 2024 - Specify file path, text to append, and the append option in standard open options. ... import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class NIOFileAppend { public static void main(String[] args) { String path = "example.txt"; String textToAdd = "Appended using NIO.\n"; try { Files.write(Paths.get(path), textToAdd.getBytes(), StandardOpenOption.APPEND); } catch (IOException e) { System.err.println("Error appending text: " + e.getMessage()); } } } Explain Code
🌐
TutorialsPoint
tutorialspoint.com › javaexamples › file_append.htm
How to append a string in an existing file using Java
This example shows how to append a string in an existing file using filewriter method. import java.io.*; public class Main { public static void main(String[] args) throws Exception { try { BufferedWriter out = new BufferedWriter(new FileWriter("filename")); out.write("aString1\n"); out.close(); out = new BufferedWriter(new FileWriter("filename",true)); out.write("aString2"); out.close(); BufferedReader in = new BufferedReader(new FileReader("filename")); String str; while ((str = in.readLine()) != null) { System.out.println(str); } } in.close(); catch (IOException e) { System.out.println("exception occoured"+ e); } } }
Find elsewhere
🌐
Greenfoot
greenfoot.org › topics › 65278 › 0
Greenfoot | Discuss | How to Append Text to an Existing File in Java
February 17, 2023 - Files.writeString(fileName, text, StandardOpenOption.APPEND); Note: Propably you will have to add the following import statement at the top of your source code: import java.nio.file.StandardOpenOption; Live long and prosper, Spock47 Thank you.
🌐
Aspose
docs.aspose.com › words › java › insert-and-append-documents
Insert and Append Documents in Java|Aspose.Words for Java
When you need to insert or append one section or paragraph to another, you essentially need to import the nodes of the first document node tree into the second one using the ImportNode method.
🌐
javaspring
javaspring.net › blog › append-in-java
Understanding `append` in Java — javaspring.net
One of the most common use cases of append is building dynamic strings. For example, you may need to build a SQL query string or a log message. Using StringBuilder or StringBuffer is more efficient than using the + operator in a loop. Here is an example of building a SQL query string using StringBuilder: import java.util.ArrayList; import java.util.List; public class SQLQueryBuilder { public static void main(String[] args) { List<String> conditions = new ArrayList<>(); conditions.add("name = 'John'"); conditions.add("age > 20"); conditions.add("city = 'New York'"); StringBuilder query = new StringBuilder("SELECT * FROM users WHERE "); for (int i = 0; i < conditions.size(); i++) { if (i > 0) { query.append(" AND "); } query.append(conditions.get(i)); } String finalQuery = query.toString(); System.out.println(finalQuery); } }
🌐
TutorialsPoint
tutorialspoint.com › What-is-the-append-method-in-Java
What is the append method in Java?
The append(char c) method of the java.lang.StringBuffer appends the string representation of the char argument to this sequence. The argument is appended to the contents of this sequence. The length of this sequence increases by 1. ... import java.lang.*; public class StringBufferDemo { public ...
🌐
Sololearn
sololearn.com › en › Discuss › 661127 › someone-can-explain-how-to-use-append-
Someone can explain how to use append() ? | Sololearn: Learn to code for FREE!
August 27, 2017 - There are several append() methods in Java. I'm going to guess that you mean the append method for a StringBuilder, since it's one of the most common. import java.lang.StringBuilder; import java.util.Scanner; public class Program { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); sb.append("Hello,"); sb.append(" World!"); System.out.println(sb.toString()); sb.delete(0,sb.length()); Scanner sc = new Scanner(System.in); System.out.println("What's your name?
🌐
Programiz
programiz.com › java-programming › examples › append-text-existing-file
Java Program to Append Text to an Existing File
Java Exception Handling · Before we append text to an existing file, we assume we have a file named test.txt in our src folder. Here's the content of test.txt · This is a Test 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 you run the program, the test.txt file now contains: This is a Test file.Added text ·
Top answer
1 of 16
929

Are you doing this for logging purposes? If so there are several libraries for this. Two of the most popular are Log4j and Logback.

Java 7+

For a one-time task, the Files class makes this easy:

try {
    Files.write(Paths.get("myfile.txt"), "the text".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
    //exception handling left as an exercise for the reader
}

Careful: The above approach will throw a NoSuchFileException if the file does not already exist. It also does not append a newline automatically (which you often want when appending to a text file). Another approach is to pass both CREATE and APPEND options, which will create the file first if it doesn't already exist:

private void write(final String s) throws IOException {
    Files.writeString(
        Path.of(System.getProperty("java.io.tmpdir"), "filename.txt"),
        s + System.lineSeparator(),
        StandardOpenOption.CREATE, StandardOpenOption.APPEND
    );
}

However, if you will be writing to the same file many times, the above snippets must open and close the file on the disk many times, which is a slow operation. In this case, a BufferedWriter is faster:

try(FileWriter fw = new FileWriter("myfile.txt", true);
    BufferedWriter bw = new BufferedWriter(fw);
    PrintWriter out = new PrintWriter(bw))
{
    out.println("the text");
    //more code
    out.println("more text");
    //more code
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

Notes:

  • The second parameter to the FileWriter constructor will tell it to append to the file, rather than writing a new file. (If the file does not exist, it will be created.)
  • Using a BufferedWriter is recommended for an expensive writer (such as FileWriter).
  • Using a PrintWriter gives you access to println syntax that you're probably used to from System.out.
  • But the BufferedWriter and PrintWriter wrappers are not strictly necessary.

Older Java

try {
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}

Exception Handling

If you need robust exception handling for older Java, it gets very verbose:

FileWriter fw = null;
BufferedWriter bw = null;
PrintWriter out = null;
try {
    fw = new FileWriter("myfile.txt", true);
    bw = new BufferedWriter(fw);
    out = new PrintWriter(bw);
    out.println("the text");
    out.close();
} catch (IOException e) {
    //exception handling left as an exercise for the reader
}
finally {
    try {
        if(out != null)
            out.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(bw != null)
            bw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
    try {
        if(fw != null)
            fw.close();
    } catch (IOException e) {
        //exception handling left as an exercise for the reader
    }
}
2 of 16
203

You can use fileWriter with a flag set to true , for appending.

try
{
    String filename= "MyFile.txt";
    FileWriter fw = new FileWriter(filename,true); //the true will append the new data
    fw.write("add a line\n");//appends the string to the file
    fw.close();
}
catch(IOException ioe)
{
    System.err.println("IOException: " + ioe.getMessage());
}
🌐
javaspring
javaspring.net › blog › what-does-append-do-in-java
Understanding the `append` Method in Java — javaspring.net
If you know approximately how many characters you will append, you can initialize the StringBuilder or StringBuffer with an appropriate capacity. This can reduce the number of internal resizing operations, improving performance. import java.util.*; public class CapacityInitialization { public static void main(String[] args) { StringBuilder sb = new StringBuilder(100); // Append characters } }
🌐
Mkyong
mkyong.com › home › java › how to append text to a file in java
How to append text to a file in Java - Mkyong.com
October 1, 2020 - 1.1 The below example shows how to append a single line to the end of a file. ... package com.mkyong.io.file; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class FileAppend1 { private static final String NEW_LINE = System.lineSeparator(); public static void main(String[] args) throws IOException { Path path = Paths.get("/home/mkyong/test/abc.txt"); appendToFile(path, "hello world" + NEW_LINE); } // Java 7 private static void appendToFile(Pat
🌐
GeeksforGeeks
geeksforgeeks.org › java › stringbuilder-append-method-in-java-with-examples
StringBuilder append() Method in Java - GeeksforGeeks
July 11, 2025 - In Java, the append() method of StringBuilder class is used to add data to the end of an existing StringBuilder object.
🌐
BeginnersBook
beginnersbook.com › 2014 › 01 › how-to-append-to-a-file-in-java
How to append to a file in java using BufferedWriter, PrintWriter
Whatever you write using PrintWriter object would be appended to the File. import java.io.File; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; class AppendFileDemo { public static void main( String[] args ) { try{ String content = "This is my content which would be appended " + "at the end of the specified file"; //Specify the file name and path here File file =new File("C://myfile.txt"); /* This logic is to create the file if the * file is not already present */ if(!file.exists()){ file.createNewFile(); } //Here true is to append the content to file File