UniversalDetector detector = new UniversalDetector(null);
ReadableByteChannel bc = Channels.newChannel(stream);
ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
int read = 0;
while ((read = bc.read(buffer)) != -1) {
detector.handleData(buffer.array(), buffer.position() - read, read);
buffer = resizeBuffer(buffer);
}
detector.dataEnd();
// copy the result back to a byte array
String encoding = detector.getDetectedCharset();