StringBuffer的乱码问题

来源:百度知道 编辑:UC知道 时间:2024/07/04 18:41:38
请看一下这段代码:
byte[] bytes = "测试".getBytes();
BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(bytes));
int c = 0;
StringBuffer result = new StringBuffer();
while ((c=is.read())!=-1) {
result.append((char) c);
}
System.out.println(result.toString());
输出结果乱码,请大侠指点,先谢谢了!
如能用最简单的方法(不添加新类)解决,再额外加分。
这只是提取了其中的一部分代码用于测试而已。这样可以吧,英文没问题,就中文出现乱码,我想到了一种解决办法,那就是
System.out.println(new String(result.toString().getBytes("ISO8859-1")));
但我想从前面下手,不知道怎么做。

这段代码没啥意义嘛,直接输出多好啊
java中的char是两个byte,你强制转换的话相当于把一个汉字转换成两个char了,所以乱码

修改如下,已测试通过。
byte[] bytes = "测试".getBytes();
byte[] b=new byte[bytes.length];
BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(bytes));
int c = 0;
while (c!=-1) {
c=is.read(b);
}
System.out.println(new String(b));

BufferedInputStream一次读的是一个字节。。
而char是两个字节,你硬生生的把他分开了
汉字char的两个字节都有内容的
英文虽然也是两个字节,但是有一个字节是全0,所以英文没有乱码,你应该一次读两个字节然后再组装

Stream的read,不管文件怎么样,read都一次只读取1个字节,也就是8位
从Reader派生的子类也有read(),这个返回的是一个unicode字符单元,即0---65535的整数。
所以改成下列情况就可以了
byte[] bytes = "测试a哈".getBytes();
BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(bytes));
BufferedReader read = new BufferedReader (new InputStreamReader(is));
int c = 0;
StringBuffer result = new StringBuffer();
while ((c=read.read())!=-1) {