1 package com.qyh.io; 2 3 import java.io.BufferedInputStream; 4 import java.io.BufferedOutputStream; 5 import java.io.FileInputStream; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 9 /* 10 * 字节流四种方式复制文件 11 * 基本字节流一次读取一个字节 12 * 基本字节流一次读取一个字节数组 13 * 高效字节流一次读取一个字节 14 * 高效字节流一次读取一个字节数组 15 */ 16 17 public class CopyImageDemo { 18 public static void main(String[] args) throws IOException { 19 method1("d:\兔子.jpg","copy1.jpg"); 20 method2("d:\兔子.jpg","copy2.jpg"); 21 method3("d:\兔子.jpg","copy3.jpg"); 22 method4("d:\兔子.jpg","copy4.jpg"); 23 } 24 25 26 //高效字节流一次读取一个字节数组 27 private static void method4(String srcString,String destString ) throws IOException { 28 //封装数据源 29 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcString)); 30 //封装目的地 31 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destString)); 32 33 byte[] bys = new byte[1024]; 34 int len = 0; 35 while((len=bis.read(bys))!=-1) { 36 bos.write(bys, 0, len); 37 } 38 bos.close(); 39 bis.close(); 40 41 } 42 43 44 // 高效字节流一次读取一个字节 45 private static void method3(String srcString , String destString ) throws IOException { 46 //封装数据源 47 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcString)); 48 //封装目的地 49 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(destString)); 50 51 int by = 0; 52 while((by=bis.read())!=-1) { 53 bos.write(by); 54 } 55 bos.close(); 56 bis.close(); 57 } 58 59 //基本字节流一次读取一个字节数组 60 private static void method2(String srcString , String destString) throws IOException { 61 //封装数据源 62 FileInputStream fis = new FileInputStream(srcString); 63 //封装目的地 64 FileOutputStream fos = new FileOutputStream(destString); 65 66 byte[] bys = new byte[1024]; 67 int len = 0; 68 while((len=fis.read(bys))!=-1) { 69 fos.write(bys, 0, len); 70 } 71 fos.close(); 72 fis.close(); 73 74 75 } 76 77 // 基本字节流一次读取一个字节 78 private static void method1(String srcString,String destString) throws IOException { 79 //封装数据源 80 FileInputStream fis = new FileInputStream(srcString); 81 //封装目的地 82 FileOutputStream fos = new FileOutputStream(destString); 83 84 int by = 0; 85 while((by=fis.read())!=-1) { 86 fos.write(by); 87 88 } 89 fos.close(); 90 fis.close(); 91 } 92 93 }