Java CloseShieldOutputStream-class And Method Code Example


Here is an example of using the CloseShieldOutputStream class from the org.apache.commons.io package in Java to create an OutputStream that can be closed multiple times without throwing an exception:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.io.output.CloseShieldOutputStream;

public class CloseShieldExample {
    public static void main(String[] args) throws IOException {
        // File to write to
        File outputFile = new File("example.txt");
        // Create a FileOutputStream for the file
        FileOutputStream fos = new FileOutputStream(outputFile);
        // Create a CloseShieldOutputStream to wrap the FileOutputStream
        CloseShieldOutputStream csos = new CloseShieldOutputStream(fos);

        // Write to the CloseShieldOutputStream
        csos.write("Hello World!".getBytes());
        // Close the CloseShieldOutputStream
        csos.close();
        // Close the CloseShieldOutputStream again
        csos.close(); // this will not throw an exception
    }
}

In this example, a FileOutputStream is created for a file named "example.txt", and a CloseShieldOutputStream is created to wrap it. The CloseShieldOutputStream is then used to write "Hello World!" to the file, and is closed twice without throwing an exception.

This is useful when you have a class that is not under your control that closes the stream and you want to write more data to it.