`
收藏列表
标题 标签 来源
文件复制 java JAVA实现简单的文件拷贝
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cn.lsd;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @date   2008-11-26 
 * @author lsd
 */
public class Cpp {
    private String sourceFile;
    private String destFile;
    
    public Cpp(String sourceFile,String destFile){
        this.sourceFile = sourceFile;
        this.destFile = destFile;
        doCopy();
    }

    private void doCopy() {
        FileInputStream in =null;
        FileOutputStream out =null;
        byte[] buffer = new byte[102400];
        try {
            in = new FileInputStream(this.sourceFile);
            File dest = new File(this.destFile);
            if(!dest.exists()){//目标文件对应的目录不存在,创建新的目录
                int index = new String(this.destFile).lastIndexOf("/");
                String path = this.destFile.substring(0, index);
                new File(path).mkdirs();
            }
            out = new FileOutputStream(this.destFile);
            int num =0;
            while((num=in.read(buffer))!=-1){
                out.write(buffer,0,num);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Cpp.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException e){
            Logger.getLogger(Cpp.class.getName()).log(Level.SEVERE, null, e);
        } finally{
            try {
                if(in!=null)
                    in.close();
                if(out!=null)
                    out.close();
            } catch (IOException ex) {
                Logger.getLogger(Cpp.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }
    }
    
    public static void main(String[] args){
        String sourceFile = "d:/颐和园yhy[小新奉献].rmvb";
        String destFile = "D:/s/sd/1.rmvb";
        long startTime =System.currentTimeMillis();
        System.out.println("start to copy");
        Cpp c= new Cpp(sourceFile,destFile);
        long endTime = System.currentTimeMillis();
        long time = (endTime-startTime)/1000;
        System.out.println("copy end;cost:"+time);
    }
     
}
Global site tag (gtag.js) - Google Analytics