背景
今天在InputStream的read()中,将byte[]存储的文本字节,转化为String进行输出时,返回的不是字符串,而是地址值。如下:
is = socket.getInputStream();
int len;
byte[] buffer= new byte[1024];
while ((len1=is.read(b1))!=-1){
System.out.println(b1.toString()); //[B@3d82c5f3
}
原因
byte[]字节数组是对象,父类Object,没有重写toString方法。因此其返回的时地址值。
解决
new String()重新构造,将byte[]字节数组转化成字符串。
public String(byte bytes[], int offset, int length)
源代码修改为:System.out.println(new String(buffer,0,len));