java ByteArrayOutputStream read()

来源:互联网 发布:国有企业发展 知乎 编辑:程序博客网 时间:2024/06/05 00:20

在看一段代码时有个疑惑

       int age = 20;       //============字节序列化==============        ByteArrayOutputStream baos= new ByteArrayOutputStream();        baos.write(int2bytes(age));        byte[] byteArray = baos.toByteArray();        System.out.println(Arrays.toString(byteArray));        //=============还原=============        ByteArrayInputStream bais= new ByteArrayInputStream(byteArray);        byte[]idBytes = new byte[4];        bais.read(idBytes);        System.out.println("age: "+ bytes2int(idBytes));

疑惑在于第10行代码 bais.read(idBytes); 没有赋值,调用后直接打印了这个字节数组,就完成了需求。我们平常用read()时都是赋值给另外一个变量,这里直接跳过了,一时没搞明白。 后来看了read()源码后

public int read(byte b[], int off, int len) throws IOException {        if (b == null) {            throw new NullPointerException();        } else if (off < 0 || len < 0 || len > b.length - off) {            throw new IndexOutOfBoundsException();        } else if (len == 0) {            return 0;        }        int c = read();        if (c == -1) {            return -1;        }        b[off] = (byte)c;        int i = 1;        try {            for (; i < len ; i++) {                c = read();                if (c == -1) {                    break;                }                b[off + i] = (byte)c;            }        } catch (IOException ee) {        }        return i;    }

虽没有用read()的返回值int,但是在传入的参数数组时,在read()方法里已经对数组(因为数组是引用传递,相当于传递的是地址,方法里面可以直接修改数组的内容)进行操作。