1 package cn.com.demo; 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 import java.io.InputStream; 9 import java.io.OutputStream; 10 11 public class StreamDemo { 12 13 public static void main(String[] args) { 14 StreamDemo streamDemo = new StreamDemo(); 15 try { 16 String srcFile = "E:\\资料\\javaEE 5.0.chm"; 17 String tarFile = "E:\\资料\\javaEE 5.0(2).chm"; 18 streamDemo.copyFile(srcFile,tarFile); 19 } catch (Exception e) { 20 e.printStackTrace(); 21 } 22 23 } 24 /** 25 * 拷贝文件,使用带缓冲功能的BufferedInputStream和BufferedOutputStream 26 * @param srcFile 27 * @param tarFile 28 * @throws IOException 29 */ 30 public void copyFile(String srcFile, String tarFile) throws IOException { 31 InputStream input = null; 32 BufferedInputStream buffInput = null; 33 OutputStream output = null; 34 BufferedOutputStream buffOutput=null; 35 try { 36 byte[] buffer = new byte[1024]; 37 int length = 0; 38 input = new FileInputStream(srcFile); 39 buffInput = new BufferedInputStream(input); 40 output = new FileOutputStream(tarFile); 41 buffOutput = new BufferedOutputStream(output); 42 while ((length = buffInput.read(buffer)) > 0) { 43 buffOutput.write(buffer,0,length); 44 } 45 buffOutput.flush(); 46 } catch (Exception e) { 47 throw new RuntimeException(e.getMessage()); 48 } finally{ 49 if (input != null){ 50 input.close(); 51 input=null; 52 } 53 if (buffInput != null){ 54 buffInput.close(); 55 buffInput=null; 56 } 57 if (output != null){ 58 output.flush(); 59 output.close(); 60 output=null; 61 } 62 if (buffOutput != null){ 63 buffOutput.close(); 64 buffOutput=null; 65 } 66 } 67 68 } 69 }