13-4 IO流 ---- 处理流之一:缓冲流(2)(字节型)实现非文本文件的复制
一、处理流之一:缓冲流的使用
1.缓冲流:
(1)BufferedInputStream
(2)BufferedOutputStream
(3)BufferedReader
(4)BufferedWriter
2.作用:提供流的读取、写入的速度
3.提高读写速度的原因:内部提供了一个缓冲区
4.处理流,就是“套接”在已有的流的基础上。
代码:
package java3;
import org.junit.Test;
import java.io.*;
//(字节型)实现非文本文件的复制
public class BufferedTest {
//实现非文本文件的复制
@Test
public void BufferedSteamTest(){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.造文件
File srcFile = new File("爱情与友情.jpg");
File destFile = new File("爱情与友情3.jpg");
//2.造流
//2.1造节点流
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
//2.2造缓冲流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//3.复制的细节:读取、写入
byte[] buffer = new byte[10];
int len;//记录每次读取的字节的个数
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer,0,len);
bos.flush();//刷新缓冲区
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源关闭
///要求:先关闭外层的流,再关闭内层的流
if(bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//说明:在关闭外层流的同时,内层流也会自动的进行关闭,所以关于内层流的关闭,可以省略。
// fos.close();
// fis.close();
}
}
//实现文件复制的方法
public void copyFileWithBuffered(String srcPath,String destPath){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.造文件
File srcFile = new File(srcPath);
File destFile = new File(destPath);
//2.造流
//2.1造节点流
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
//2.2造缓冲流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//3.复制的细节:读取、写入
byte[] buffer = new byte[2];
int len;//记录每次读取的字节的个数
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源关闭
///要求:先关闭外层的流,再关闭内层的流
if(bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@Test
public void testCopyFileWithBuffered(){
long start = System.currentTimeMillis();
String srcPath = "爱情与友情.jpg";
String destPath = "爱情与友情4.jpg";
copyFileWithBuffered(srcPath,destPath);
long end = System.currentTimeMillis();
System.out.println("复制操作花费的时间为: " + (end - start));//262 - 8
}
}
输出:
复制操作花费的时间为: 8