[英]Downloading online text with different encodings
我正在下載可以由用戶上傳的在線文本,因此文本可以是UTF-8,ISO-8859-1等。
問題是我不知道用戶使用的是哪種編碼,如果用戶上傳了UTF-8文本,則可以正常使用,但是如果用戶上傳的是帶有重音符號的ISO-8859-1文本(áé等。 。)這些字符無法正確顯示。
我試圖將文本編碼強制為UTF-8,但並非在所有情況下都適用(buffer.toString(“ UTF-8”))
這是我的代碼:
javaUrl = new URL(URLParser.parse(textResource.getUrlStr()));
connection = javaUrl.openConnection();
connection.setConnectTimeout(2000);
connection.setReadTimeout(2000);
InputStream input = new BufferedInputStream(connection.getInputStream());
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
try{
byte [] data = new byte [1024];
while ((nRead = input.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
total = buffer.toString();
}finally{
input.close();
buffer.close();
}
由於您有多種可能的編碼,而且您不知道哪種正確,因此別無選擇,只能在這里使用CharsetDecoder
。
計划:
InputStream
; byte[]
數組; 這是找到正確編碼的一種可能方法:
public boolean isCharset(final Charset charset, final byte[] contents)
throws IOException
{
final CharsetDecoder decoder = charset.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT);
final ByteBuffer buf = ByteBuffer.wrap(contents);
try {
decoder.decode(buf);
return true;
} catch (CharacterCodingException ignored) {
return false;
}
}
嘗試使用不同的編碼集(最好從UTF-8開始)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.