package com.winson.iotest;
import org.junit.Test;
import java.io.*;
/**
* @description: 输入、输出缓冲流整合(实现图片复制)
* @date: 2020/7/5 21:02
* @author: winson
*/
public class BufferedInputStreamBufferedOutputStreamTest {
@Test
public void test1() {
BufferedInputStream bufferedInputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try {
//1、造文件
File srcFile = new File("ludashi.jpg");
File desFile = new File("ludashi_out.jpg");
//2、造节点流
FileInputStream fileInputStream = new FileInputStream(srcFile);
FileOutputStream fileOutputStream = new FileOutputStream(desFile);
//3、造缓冲流
bufferedInputStream = new BufferedInputStream(fileInputStream);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
//4、复制的细节:读取、写入
byte[] bytes = new byte[1024];
int len;
while ((len = bufferedInputStream.read(bytes)) != -1) {
bufferedOutputStream.write(bytes, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4、资源关闭:先关闭外层的流,再关闭内层的流
//说明:关闭外层的流的同时,内层流也会自动的关闭,所以内层流的关闭可以省略;
try {
bufferedOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
bufferedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
原文:https://www.cnblogs.com/elnimo/p/13251879.html