To detect the encoding of a byte stream, follow these steps using org.mozilla.universalchardet.UniversalDetector:
- Instantiate: Create a new
UniversalDetector. - Feed Data: Call
handleData(byte[] buf, int offset, int length) repeatedly with chunks of data (typically a few thousand bytes). - Signal End: Call
dataEnd() once all data has been processed. - Retrieve Result: Call
getDetectedCharset() to get the name of the detected encoding as a String. - Reset: Call
reset() if you intend to reuse the same detector instance for a different detection task.
Note: You can check isDone() during the data feeding loop to stop early if the detector has already reached a confident conclusion.
import org.mozilla.universalchardet.UniversalDetector;
public class TestDetector
{
public static void main(String[] args)
{
byte[] buf = new byte[4096];
java.io.InputStream fis = java.nio.file.Files.newInputStream(java.nio.file.Paths.get("test.txt"));
// (1) Construct instance
UniversalDetector detector = new UniversalDetector();
// (2) Feed data
int nread;
while ((nread = fis.read(buf)) > 0 && !detector.isDone()) {
detector.handleData(buf, 0, nread);
}
// (3) Notify end of data
detector.dataEnd();
// (4) Get detected encoding
String encoding = detector.getDetectedCharset();
if (encoding != null) {
System.out.println("Detected encoding = " + encoding);
} else {
System.out.println("No encoding detected.");
}
// (5) Reset for reuse
detector.reset();
}
}