Java IOUtils-class And Method Code Example


Here's an example of how to use the IOUtils class from the Apache Commons IO library:

import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;

public class Example {
    public static void main(String[] args) {
        FileInputStream inputStream = null;
        try {
            inputStream = new FileInputStream("example.txt");
            byte[] data = IOUtils.toByteArray(inputStream);
            String content = new String(data, "UTF-8");
            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
    }
}

In this example, a FileInputStream is created to read the contents of a file named "example.txt". The toByteArray(InputStream) method of the IOUtils class is used to read the contents of the file into a byte array. The byte array is then converted to a String using the UTF-8 encoding. The file content is then printed to the console. Finally, the closeQuietly(InputStream) method is used to close the input stream, suppressing any exceptions that might be thrown.

Note: The IOUtils class provides a convenient set of methods for working with InputStreams, OutputStreams and Readers/Writers. This class contains utility methods for working with InputStreams, OutputStreams, and Reader/Writers, which will automatically close the stream when the end of the stream is reached.