package com.zhiyou100.io.demo02;
/*
文件复制练习:复制一张图片
确定:
数据源:C:\Users\admin\Desktop\3.gif
目的地:day29_IO\3.gif
文件复制的步骤:
*/
import java.io.*;
public class Demo05CopyImageFile {
public static void main(String[] args) throws IOException {
// show01();
show02();
}
// 使用缓冲流完成文件复制
public static void show02() throws IOException {
// 获取开始的时间
long start = System.currentTimeMillis();
// 1.构建一个字节缓冲输入流
final BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\Users\\admin\\Desktop\\3.gif"));
// 2.构建一个字节缓冲输出流
final BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("E:\\documents\\day29_IO\\3.gif"));
// 3.使用字节缓冲输入流对象中的方法read(byte[] b),读取文件
byte[] bytes = new byte[1024];
// 确定while循环结束的条件 read() == -1
int len = 0;// 记录读取到的有效字节个数
while ((len = bis.read(bytes)) != -1) {
// 4. 把读取到的字节内容再次写入到目的地文件中,调用write
bos.write(bytes, 0, len);
}
// 5.释放资源
bos.close();
bis.close();
// 获取结束的时间
long end = System.currentTimeMillis();
System.out.println("文件复制耗费的时间为:" + (end - start) + "ms");// 文件复制耗费的时间为:91ms
}
// 不使用缓冲流的操作
public static void show01() throws IOException {
// 获取开始的时间
long start = System.currentTimeMillis();
// 1. 构建字节输入流对象
final FileInputStream fis = new FileInputStream("C:\\Users\\admin\\Desktop\\3.gif");
// 2. 构建一个字节输出流对象
final FileOutputStream fos = new FileOutputStream("day29_IO\\3.gif");
// 3. 调用字节输入流对象中的方法read(byte[] b) 读取文件
final byte[] bytes = new byte[1024];
int len = 0;// 记录读取到有效字节个数
while ((len = fis.read(bytes)) != -1) {
// 4. 把读取到的字节内容写入到目的地文件中,调用write(byte[] b,int off,int len)
fos.write(bytes,0,len);
}
// 5. 释放资源 先开后关
fos.close();
fis.close();
// 获取结束的时间
long end = System.currentTimeMillis();
System.out.println("文件复制耗费的时间为:" + (end - start) + "ms");// 文件复制耗费的时间为:337ms
}
}
字节缓冲流完成文件复制
最新推荐文章于 2023-01-19 13:46:59 发布