当我在处理编码方式是8bit的网络数据流时,出现了一个问题,就是中文全部变成了乱码,经过仔细排查,发现问题出现在读取网络数据流那个函数上,因为我需要根据数据流中的某个字节来截取数据流,所以我的函数中是一个字节一个字节进行流读取的。
原本的函数:
public String read(InputStream is){
StringBuffer sb = new StringBuffer(); //用来装载字节
try {
int c = 0;
while ((c = is.read()) != '/r' ) {
if (c != '/n') {
sb.append((char)c);
}
}
} catch(Exception e) {
e.printStackTrace();
}
String s = sb.toString();
sb = null;
return s;
}
这个函数对英文数据流处理的很好,但对中文数据流处理时就会出现乱码,原因在于sb.append((char)c),这样的处理在碰到中文时会破环原本的流。
改进后的函数:
public String readLine(InputStream is){
ByteArrayOutputStream temp_baos = new ByteArrayOutputStream();
try {
int c = 0;
while ((c = is.read()) != '/r' ) {
if (c != '/n') {
temp_baos.write(c);
}
}
} catch(Exception e) {
e.printStackTrace();
}
String s = temp_baos.toString();
temp_baos = null;
return s;
}
改进后的方法使用了ByteArrayOutputStream类,用temp_baos.write可以保持流的原汁原味,无论原来的流是中文的还是英文的。
大家可以参考这个思想。