Search in sources :

Example 1 with BOMInputStream

use of com.mucommander.commons.io.bom.BOMInputStream in project mucommander by mucommander.

the class BinaryDetector method guessBinary.

/**
 * Tries and detect whether the given bytes correspond to binary or text data. The specified bytes can typically
 * be the beginning of a file.</br>
 * This method returns <code>true</code> if it thinks that the bytes correspond to binary data.
 *
 * @param b the data to analyze
 * @param off specifies where to start reading the array
 * @param len specifies where to stop reading the array
 * @return true if BinaryDetector thinks that the specified data is binary
 */
public static boolean guessBinary(byte[] b, int off, int len) {
    // So first, we try and look for a BOM (byte-order mark) to see if the stream is UTF-16 or UTF-32 encoded.
    try (BOMInputStream bin = new BOMInputStream(new ByteArrayInputStream(b, off, len))) {
        BOM bom = bin.getBOM();
        if (bom != null) {
            if (bom.equals(BOMConstants.UTF16_BE_BOM) || bom.equals(BOMConstants.UTF16_LE_BOM) || bom.equals(BOMConstants.UTF32_BE_BOM) || bom.equals(BOMConstants.UTF32_LE_BOM)) {
                return false;
            }
        }
        // No BOM, start looking for zeros
        int i;
        while ((i = bin.read()) != -1) if (i == 0x00)
            return true;
    } catch (IOException e) {
    // Can never happen in practice with a ByteArrayInputStream.
    }
    return false;
}
Also used : BOM(com.mucommander.commons.io.bom.BOM) BOMInputStream(com.mucommander.commons.io.bom.BOMInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) IOException(java.io.IOException)

Example 2 with BOMInputStream

use of com.mucommander.commons.io.bom.BOMInputStream in project mucommander by mucommander.

the class TextViewer method loadDocument.

void loadDocument(InputStream in, final String encoding, DocumentListener documentListener) throws IOException {
    // (see ticket #245)
    if (encoding != null && encoding.toLowerCase().startsWith("utf")) {
        in = new BOMInputStream(in);
    }
    // If the given encoding is invalid (null or not supported), default to "UTF-8"
    this.encoding = encoding == null || !Charset.isSupported(encoding) ? "UTF-8" : encoding;
    textEditorImpl.read(new BufferedReader(new InputStreamReader(in, this.encoding)));
    // Listen to document changes
    if (documentListener != null)
        textEditorImpl.addDocumentListener(documentListener);
}
Also used : BOMInputStream(com.mucommander.commons.io.bom.BOMInputStream) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader)

Aggregations

BOMInputStream (com.mucommander.commons.io.bom.BOMInputStream)2 BOM (com.mucommander.commons.io.bom.BOM)1 BufferedReader (java.io.BufferedReader)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 IOException (java.io.IOException)1 InputStreamReader (java.io.InputStreamReader)1