- ByteArrayInputStream:将字节数组转成字节输入流
- ByteArrayOutputStream:从字节数组输出流可以获取字节数组
// 测试文件大小:2487KB
// 文件转为字节数组
public static byte[] ioOption() throws IOException {
// 缓冲字节输入流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("D:/demo.txt")));
// 字节数组输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len;
while((len = bis.read(bytes))!=-1){
baos.write(bytes,0,len);
}
bis.close();
baos.close();
return baos.toByteArray();
}
输出:
耗时(毫秒):8
// 测试文件大小:2487KB
// 字节数组转为文件
public static void ioOption(byte[] bytes) throws IOException {
// 字节数组输入流
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
// 缓冲字节输出流
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("D:/copy.txt")));
byte[] buffer = new byte[1024];
int len;
while((len = bais.read(buffer))!=-1){
bos.write(buffer,0,len);
}
bais.close();
bos.close();
}
输出:
耗时(毫秒):13
- 将对象转为字节数组、字节数组转为对象(深克隆技术的一种实现方式)
// Student 类必须实现 Serializable 接口
// 对象转为字节数组
public static byte[] ioOption(Student student) throws IOException {
// 字节数组输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
// 对象字节输出流
ObjectOutputStream oos = new ObjectOutputStream(baos);
// 将对象写进 baos
oos.writeObject(student);
baos.close();
oos.close();
return baos.toByteArray();
}
// Student 类必须实现 Serializable 接口
// 字节数组转为对象
public static Student ioOption(byte[] bytes) throws IOException, ClassNotFoundException {
// 字节数组输入流
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
// 缓冲字节输出流
ObjectInputStream ois = new ObjectInputStream(bais);
return (Student) ois.readObject();
}