1.ByteArrayOutputStream
官方解释:
该类实现了将数据写入字节数组的输出流。 当数据写入缓冲区时,缓冲区会自动增长。 可以使用toByteArray()和toString()检索数据。
关闭ByteArrayOutputStream没有任何效果。 在关闭流之后,可以调用此类中的方法,而不生成IOException 。
作用:把流中的数据写到字节数组中
示例:
fos.txt:
public void demo01(){
try(BufferedInputStream bis = new BufferedInputStream(new FileInputStream("D:\\project\\study_project\\javase\\src\\test\\java\\com\\zhangzemin\\io\\byte_straem\\fos.txt"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
){
byte[] bytes = new byte[1024];
int len;
while ((len = bis.read(bytes)) != -1){
baos.write(bytes,0,len);
}
byte[] content = baos.toByteArray();
System.out.println(content.length);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
输出结果:
4
应用场景:把文件以字节数组方式存储到数据库中。
注:数据中使用blob
数据类型接收,实体类用byte[]
传输
2.ByteArrayInputStream
官方解释:
ByteArrayInputStream包含一个内部缓冲区,其中包含可以从流中读取的字节。 内部计数器跟踪由read方法提供的下一个字节。
关闭一个ByteArrayInputStream没有任何效果。 该流中的方法可以在流关闭后调用,而不生成IOException 。
示例:
public void demo02(){
byte[] byteStr = "HelloWorld".getBytes();
try(ByteArrayInputStream bais = new ByteArrayInputStream(byteStr)){
byte[] bytes = new byte[1024];
int len;
while ((len = bais.read(bytes)) != -1){
String s = new String(bytes,0,len);
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
运行结果:
HelloWorld