1 回答
TA貢獻1772條經驗 獲得超8個贊
我需要識別編碼并正確處理數據。為此,我使用了 UniversalDetectororg.mozilla.universalchardet.UniversalDetector
private static final UniversalDetector DETECTOR = new UniversalDetector(null);
private static String getEncode(byte[] data) throws IOException {
DETECTOR.reset();
byte[] buf = new byte[data.length];
InputStream is = new ByteArrayInputStream(data);
int read;
while ((read = is.read(buf)) > 0 && !DETECTOR.isDone()) {
DETECTOR.handleData(buf, 0, read);
}
is.close();
DETECTOR.dataEnd();
return DETECTOR.getDetectedCharset();
}
然后我用正確的編碼閱讀它:
private static String readWithEncode(byte[] data, String encoding) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data), encoding));
StringBuilder result = new StringBuilder();
String s;
while ((s = br.readLine()) != null) {
result.append(s);
}
br.close();
return result.toString();
}
添加回答
舉報
