Java FilterCollectionWriter-class And Method Code Example


Here is an example of using the FilterCollectionWriter class from the org.apache.commons.io package in Java to write a collection of objects to a file using a filter:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.output.FilterCollectionWriter;

public class FilterCollectionWriterExample {
    public static void main(String[] args) throws IOException {
        // File to write to
        File outputFile = new File("example.txt");
        // Create a FileWriter for the file
        FileWriter fw = new FileWriter(outputFile);
        // Create a FilterCollectionWriter with a filter
        FilterCollectionWriter fcw = new FilterCollectionWriter(fw, (s) -> s.toUpperCase());
        
        // Sample data
        List<String> data = Arrays.asList("Hello", "world", "!");

        // Write the data to the file using the FilterCollectionWriter
        IOUtils.writeLines(data, "\n", fcw);
        // Close the FilterCollectionWriter
        fcw.close();
    }
}

In this example, a FileWriter is created for a file named "example.txt" and a FilterCollectionWriter is created to wrap it and take a function that converts the string to upper case . The FilterCollectionWriter is then used to write a collection of string to the file, and the function passed will convert each string to upper case before writing.

This class is useful when you need to filter the data before writing it to an output stream. It allows you to easily filter a collection of objects before writing them to an output stream.