Java AppendableOutputStream-class And Method Code Example


Here is an example of using the AppendableOutputStream class from the Apache Commons IO library in Java to append data to an existing file:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.io.output.AppendableOutputStream;

public class AppendableOutputStreamExample {
    public static void main(String[] args) {
        // specify the file to append data to
        File file = new File("/path/to/file.txt");
        
        try (AppendableOutputStream out = new AppendableOutputStream(new FileOutputStream(file, true))) {
            // write data to the file
            out.write("This is some text to be appended to the file.".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In this example, the AppendableOutputStream is created using a FileOutputStream set to append mode (new FileOutputStream(file, true)) and passed as an argument to AppendableOutputStream, the data is then written to the file using the write() method of the AppendableOutputStream class.

You can also use the write(byte[] b, int off, int len) or write(int b) to write the data to the output stream.

Note that in this example, the try-with-resources statement is used to automatically close the output stream after the data is written to the file. This is a good practice to ensure that the resources are properly closed and avoid potential memory leaks.