一)ByteArrayOutputStream介绍
概述:该类实现了将数据写入字节数组的输出流。 当数据写入缓冲区时,缓冲区会自动增长。 数据可以使用toByteArray()和toString() 。
初始化构造方法:
1、ByteArrayOutputStream()
创建一个新的字节数组输出流。 默认的大小为32。
2、ByteArrayOutputStream(int size)
创建一个新的字节数组输出流,具有指定大小的缓冲区容量(以字节为单位)。
二)ByteArrayOutputStream场景详解
场景一:默认构造方法
/**
* 场景一
*/
public static void method1() {
InputStream in = null;
ByteArrayOutputStream out = null;
try {
in = new FileInputStream(new File("D:\\io\\a.txt"));
out = new ByteArrayOutputStream();
byte[] bytes = new byte[1024*8];
int len = 0;
while((len = in.read(bytes)) != -1){
out.write(bytes, 0, len);
}
System.out.println(out.toString("GBK"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
场景二:指定大小数组构造方法
/**
* 场景二
*/
public static void method2() {
InputStream in = null;
ByteArrayOutputStream out = null;
try {
in = new FileInputStream(new File("D:\\io\\a.txt"));
out = new ByteArrayOutputStream(32);
int len = 0;
while((len = in.read()) != -1){
out.write(len);
}
System.out.println(out.toString("GBK"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
识别二维码关注个人微信公众号
本章完结,待续,欢迎转载!
本文说明:该文章属于原创,如需转载,请标明文章转载来源!