* or null if not detected
* @throws IOException
*/
public static String getFileCharset(File file) throws IOException {
byte[] buf = new byte[4096];
final UniversalDetector universalDetector;
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file))) {
universalDetector = new UniversalDetector(null);
int numberOfBytesRead;
while ((numberOfBytesRead = bufferedInputStream.read(buf)) > 0 && !universalDetector.isDone()) {
universalDetector.handleData(buf, 0, numberOfBytesRead);
}
}
universalDetector.dataEnd();
String encoding = universalDetector.getDetectedCharset();
if (encoding != null) {
LOGGER.debug("Detected encoding for {} is {}.", file.getAbsolutePath(), encoding);
} else {
LOGGER.debug("No encoding detected for {}.", file.getAbsolutePath());
}
universalDetector.reset();
return encoding;
}