12 缓冲流+字节流 实现文件拷贝(性能提升)

package bufferedIO;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/*
 * 字节流文件拷贝+缓冲流,提高性能
 * 缓冲流(节点流)
 */
public class BufferedByte {
    public static void copyFile(String srcPath,String destPath) 
            throws Exception {
        
        //1 建立联系 :  File对象 (源头----目的地)
        //源头文件必须存在,目的地文件可以不存在
        File src = new File(srcPath);
        File dest = new File(destPath);
        
        if(! src.isFile()){
            System.out.println("只能拷贝文件");
            throw new IOException("只能拷贝文件");
        }
        //2  选择流
        InputStream is = new BufferedInputStream(
                new FileInputStream(src));
        
        OutputStream os = new BufferedOutputStream(
                new FileOutputStream(dest));
        
        //3  文件拷贝(循环+读取+写出)
        byte[] flush = new byte[1024];
        int length;
        
        //读取
        while((length = is.read(flush)) != -1){
            //写出
            os.write(flush, 0, length);
        }
        os.close();
        is.close();
    }
}


你可能感兴趣的:(12 缓冲流+字节流 实现文件拷贝(性能提升))