public class Test {
public static void main(String[] args) {
byte[] b = new byte[4];
for(byte bb : b) {
System.out.println(bb);
}
System.out.println(new String(b, 0, b.length));
}
}为什么最后一行打印出来的是四个方框而不是0000?

解决方案 »

  1.   

    为什么要是 0000 啊?String 构造中如果有 byte 数组的话,那就会按照操作系统默认的字符集将 byte 数组组合成字符串的。
    因此就组成 4 个 Unicode 编码为 0 的字符了,编码为 0 的字符属于不可显示的控制字符,因此在 Eclipse
    中会显示成小方块。
      

  2.   

    举个例子吧:“新年好”的 GBK 编码是 D0C2, C4EA, BAC3,下面的代码就是将打散的字节重新组合。public class Test2 {    public static void main(String[] args) {        
            byte[] bys = { (byte)0xd0, (byte)0xc2, (byte)0xc4, (byte)0xea, (byte)0xba, (byte)0xc3 };
            String str = new String(bys);
            System.out.println(str);
        }
    }
      

  3.   

    根据String 源码:
    public String(byte bytes[], int offset, int length) {
            checkBounds(bytes, offset, length);
            char[] v  = StringCoding.decode(bytes, offset, length);
            this.offset = 0;
            this.count = v.length;
            this.value = v;
        }
    先把字节转换成字符数组。
    所以,当你的参数这样写:
    byte[] b = new byte[]{'0','0','0','0'};
    或者
    改用StringBuffer就没事了。
    public static void main(String[] arg) {
    byte[] b = new byte[4];
    StringBuffer s = new StringBuffer();
    for (byte bb : b) {
    System.out.println(bb);
    s.append(bb);
    }

    System.out.println(s);
    }