如何在android中设置字符串字符编码
问题描述:
HI!我有一个在ISO-8859-2编码的网页内容。如何将编码在这个字符集中的流转换为java的UTF-8。我试着下面的代码,但它不工作。它弄乱了一些字符。是否有其他方法可以做到这一点?
HI! I have a web page content in encoded in ISO-8859-2. How to convert a stream encoded in this charset to java's UTF-8. I'm trying the code below, but it does not work. It messes up some characters. Is there some other way to do this?
BufferedInputStream inp = new BufferedInputStream(in);
byte[] buffer = new byte[8192];
int len1 = 0;
try{
while ( (len1 = inp.read(buffer)) != -1 )
{
String buff = new String(buffer,0,len1,"ISO-8859-2");
stranica.append(buff);
}
答
使用InputStreamReader Charset:
Try it with an InputStreamReader and Charset:
InputStreamReader inp = new InputStreamReader(in, Charset.forName("ISO-8859-2"));
BufferedReader rd = new BufferedReader(inp);
String l;
while ((l = rd.readLine()) != null) {
...
}
如果你得到 UnsupportedCharsetException
,你知道你的问题是什么...另外,用 inp.getEncoding ()
,您可以检查实际使用的编码。
If you get an UnsupportedCharsetException
, you know what's your problem... Also, with inp.getEncoding()
you can check which encoding is really used.