Java BOMInputStream-class And Method Code Example


Here is an example of how to use the BOMInputStream class from the Apache Commons IO library in Java:

import java.io.FileInputStream;
import java.io.IOException;
import org.apache.commons.io.input.BOMInputStream;

public class MyClass {
    public static void main(String[] args) throws IOException {
        FileInputStream inputStream = new FileInputStream("example.txt");
        try (BOMInputStream bomInputStream = new BOMInputStream(inputStream)) {
            byte[] bom = bomInputStream.getBOM();
            if (bom != null) {
                System.out.println("BOM found: " + new String(bom, "UTF-8"));
            } else {
                System.out.println("No BOM found");
            }
            int nextByte = bomInputStream.read();
            while (nextByte != -1) {
                // do something with the byte
                nextByte = bomInputStream.read();
            }
        }
    }
}

In this example, BOMInputStream is wrapping a FileInputStream for the file "example.txt".

It automatically detects and skips a byte order mark (BOM) from the input stream if present. The BOM could be present in a file encoded in UTF-8, UTF-16LE, UTF-16BE and UTF-32LE, UTF-32BE.

The try-with-resources statement is used to automatically close the BOMInputStream when the try block is exited. This also ensures that inputStream is also closed as it is being wrapped by BOMInputStream.

The BOMInputStream is used in the same way as any other InputStream, in this case it reads a byte at a time until the end of the file is reached. The method getBOM() returns the byte[] array of the BOM found if any.

Please note that this is a simple example and in real-world usage, you might want to do more complex processing on the bytes before returning them.