import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; /** * 将桌面证件照复制一份到桌面(从磁盘中读入一个文件并写入另一个文件) * 使用BufferedInputStream和BufferedOutputStream实现非文本文件复制(5s) * 比FileInputStream和FileOutputStream更快(18s) * * @author pomay * */ public class CopyFile { public void copy(String begin, String end) { // 3.将创建的节点流的对象作为形参传递给缓冲流的构造器中 BufferedInputStream bis = null; BufferedOutputStream bos = null; try { // 1.提供读入、写出的流 File file1 = new File(begin); File file2 = new File(end); // 2.创建相应的节点流 FileInputStream fis = new FileInputStream(file1); FileOutputStream fos = new FileOutputStream(file2); bis = new BufferedInputStream(fis); bos = new BufferedOutputStream(fos); // 4.实现文件的复制 byte[] b = new byte[20];// 每次运20个,可按照实际文件大小调整 int len; while ((len = bis.read(b)) != -1) bos.write(b, 0, len); } catch ( Exception e) { e.printStackTrace(); } finally {// 关闭相应的流 if (bos != null) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (bis != null) try { bis.close(); } catch (IOException e) { e.printStackTrace(); } } } } } public static void main(String[] args) { String begin = "C:\\Users\\Desktop\\1.jpg"; String end = "C:\\Users\\Desktop\\2.jpg"; CopyFile c = new CopyFile(); long startTime = System.currentTimeMillis(); c.copy(begin, end); long endTime = System.currentTimeMillis(); System.out.println("拷贝图片花费时间为:" + (endTime - startTime));// 5s } }