Java Text File Read by Charset inferCharset(byte[] bytes, int bytesRead, Charset clientCharset)

Here you can find the source of inferCharset(byte[] bytes, int bytesRead, Charset clientCharset)

Description

Try to determine whether a byte buffer's character encoding is that of the passed-in charset.

License

Open Source License

Declaration

public static boolean inferCharset(byte[] bytes, int bytesRead, Charset clientCharset) 

Method Source Code


//package com.java2s;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CoderResult;
import java.nio.charset.CodingErrorAction;

public class Main {
    /**/*from  w w  w.j a v  a 2s  . c  o m*/
     * Try to determine whether a byte buffer's character encoding is that of the
     * passed-in charset. Uses inefficient
     * heuristics that will be revisited when we're more familiar with likely
     * usage patterns.
     * 
     * Note this has been heavily changed since inception and will
     * almost certainly disappear in the 10.x timeframe -- HR.
     */
    public static boolean inferCharset(byte[] bytes, int bytesRead, Charset clientCharset) {
        ByteBuffer byteBuf = ByteBuffer.wrap(bytes, 0, bytesRead);
        CharBuffer charBuf = CharBuffer.allocate(byteBuf.capacity() * 2);

        if (clientCharset != null) {
            CharsetDecoder decoder = clientCharset.newDecoder();
            decoder.onMalformedInput(CodingErrorAction.REPORT);
            decoder.onUnmappableCharacter(CodingErrorAction.REPORT);
            CoderResult coderResult = decoder.decode(byteBuf, charBuf, false);
            if (coderResult != null) {
                if (coderResult.isError()) {
                    // Wasn't this one...
                    return false;
                } else {
                    return true; // Still only *probably* true, dammit...
                }
            }
        }

        return true;
    }
}

Related

  1. getInputStreamReader(InputStream stream, Charset charset)
  2. getReader(InputStream in, String charsetName)
  3. getReader(InputStream is, String charset)
  4. getReader(String fileName, Charset cs)
  5. getReader(String path, Charset encoding)
  6. initDecoder(Charset charset, ThreadLocal> localDecoder)
  7. inputStreamToString(InputStream input, Charset charset, boolean closeInputAfterRead)
  8. newBufferedFileReader(File file, Charset charset)
  9. newBufferedReader(URL url, Charset cs)