原创首发
ByteArrayOutputStream和ByteArrayInputStream应用场景

ByteArrayOutputStream和ByteArrayInputStream应用场景
这两个是好东西,在某些情况下,是很好用的。
先看看介绍吧
- ByteArrayOutputStream
/**
* This class implements an output stream in which the data is
* written into a byte array. The buffer automatically grows as data
* is written to it.
* The data can be retrieved using <code>toByteArray()</code> and
* <code>toString()</code>.
* <p>
* Closing a <tt>ByteArrayOutputStream</tt> has no effect. The methods in
* this class can be called after the stream has been closed without
* generating an <tt>IOException</tt>.
*
* @author Arthur van Hoff
* @since JDK1.0
*/
JDK1.0就有了。
The buffer automatically grows as data is written to it。自动增长的Buffer。
如果说,在某些情况下,你直接操作byte[],比如你遇到某个byte要进行转换成两个byte,在不定的情况下。你是不是不好创建byte[]的长度呀?
这个时候,就可以使用ByteArrayStream了。
- ByteArrayOutputStream
/**
* A <code>ByteArrayInputStream</code> contains
* an internal buffer that contains bytes that
* may be read from the stream. An internal
* counter keeps track of the next byte to
* be supplied by the <code>read</code> method.
* <p>
* Closing a <tt>ByteArrayInputStream</tt> has no effect. The methods in
* this class can be called after the stream has been closed without
* generating an <tt>IOException</tt>.
*
* @author Arthur van Hoff
* @see java.io.StringBufferInputStream
* @since JDK1.0
*/
ByteArrayOutputStream 也是类似的。那么一个in,一个out,看名字就知道了。
in是read,out的是write
应用场景
- 比如说上传COS文件到第三方服务器。如果你要在你的服务器上做一些处理,你不写到文件里。只写到内存里就可以通过ByteArrayInputStream来完成临时的存储了。对里面的数据进行读取即可。
- 如果说你要对字节数组里的内容进行转换,并且你不知道动态的长度是多少。我们在创建数组时是要指定长度的。这个时候我们就可以写到ByteArrayOutputStream里了。然后再一次转成byte[]。
ByteArrayInputStream
比如说你要操作MultipartFile,计算MD5值,如果你直接操作,那么它的读取角标位置就错了。你要么reset一下,要么就用一个buffer存储起来,单独计算md5值,这个时候,我们就可以通过ByteArrayInputStream来完成了。
直接通过构造方法就可以传入byte[]
ByteArrayOutputStream
比如说我这里需要对数据进行转换:
//往外发的数据
// 0X7D --> 0X7D 0X01
// 0X5B --> 0X7D 0X02
// 0X5D --> 0X7D 0X03
// 0X2C --> 0X7D 0X04
// 0X2A --> 0X7D 0X05
//先挖个坑
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte a = 0X7D;
for (byte b : source) {
if (b == 0X7D) {
outputStream.write(a);
outputStream.write(0X01);
} else if (b == 0X5B) {
outputStream.write(a);
outputStream.write(0X02);
} else if (b == 0X5D) {
outputStream.write(a);
outputStream.write(0X03);
} else if (b == 0X2C) {
outputStream.write(a);
outputStream.write(0X04);
} else if (b == 0X2A) {
outputStream.write(a);
outputStream.write(0X05);
} else {
outputStream.write(b);
}
}
return outputStream.toByteArray();