How do I append and replace content of a StringBuffer?

A StringBuffer is like a String, but can be modified. StringBuffer are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order that is consistent with the order of the method calls made by each of the individual threads involved.

As of release JDK 1.5, this class has been supplemented with an equivalent class designed for use by a single thread, the StringBuilder. The StringBuilder class should generally be used in preference to this one, as it supports all the operations, but it is faster, as it performs no synchronization.

package org.kodejava.lang;

public class StringBufferAppendReplace {
    public static void main(String[] args) {
        StringBuffer quote = new StringBuffer("an apple ");
        char a = 'a';
        String day = " day";
        StringBuffer sentences = new StringBuffer(" keep the doctor away");

        // Append a character into StringBuffer
        quote.append(a);
        System.out.println("quote = " + quote);

        // Append a string into StringBuffer
        quote.append(day);
        System.out.println("quote = " + quote);

        // Append another StringBuffer
        quote.append(sentences);
        System.out.println("quote = " + quote);

        // Replace a sub string from StringBuffer starting
        // from index = 3 to index = 8
        quote.replace(3, 8, "orange");
        System.out.println("quote = " + quote);
    }
}

Here is our program output:

quote = an apple a
quote = an apple a day
quote = an apple a day keep the doctor away
quote = an orange a day keep the doctor away

How do I append data to a text file?

One of the common task related to a text file is to append or add some contents to the file. It’s really simple to do this in Java using a FileWriter class. This class has a constructor that accept a boolean parameter call append. By setting this value to true a new data will be appended at the end of the file when we write a new data to it.

Let’s see an example.

package org.kodejava.io;

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

public class AppendFileExample {
    public static void main(String[] args) {
        File file = new File("user.txt");

        try (FileWriter writer = new FileWriter(file, true)) {
            writer.write("username=kodejava;password=secret" + System.lineSeparator());
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}