日期:2014-05-20  浏览次数:20980 次

怎样将字节流转换成字符流?
网络编程里面 ,Socket 只能得到字节流,但是我传字符串的时候 ,就会出现乱码的情况,请问该如何将字节流转换成字符流?

------解决方案--------------------
String

public String(byte[] bytes,
String charsetName)
throws UnsupportedEncodingException
Constructs a new String by decoding the specified array of bytes using the specified charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array.
The behavior of this constructor when the given bytes are not valid in the given charset is unspecified. The CharsetDecoder class should be used when more control over the decoding process is required.

Parameters:
bytes - the bytes to be decoded into characters
charsetName - the name of a supported charset
Throws:
UnsupportedEncodingException - If the named charset is not supported
Since:
JDK1.1
------解决方案--------------------
从字节流转化为字符流时,实际上就是byte[]转化为String时, 
public String(byte bytes[], String charsetName) 
有一个关键的参数字符集编码,通常我们都省略了,那系统就用操作系统的lang 
而在字符流转化为字节流时,实际上是String转化为byte[]时, 
byte[] String.getBytes(String charsetName) 

------解决方案--------------------
选用InputStreamReader类
------解决方案--------------------
顶2楼,正解