1. 程式人生 > 實用技巧 >Java檔案遞迴拷貝

Java檔案遞迴拷貝

import java.io.*;

/**
 * @Author langkye
 */
public class FileCopy{
    public static void main(String[] args) {
        //源目錄
        String srcDir = "D:\\src";
        //目標目錄
        String targetDir = "D:\\target";

        File src = new File(srcDir);
        File target = new File(targetDir);

        reCopyFiles(src,target);
    }

    public static void reCopyFiles(File src, File target){
        //如果src是目錄
        if (src.isDirectory()){
            //在目標目錄下建立src的資料夾
            File t = new File(target.getAbsoluteFile()+File.separator+src.getName());
            t.mkdirs();
            for (File s :src.listFiles()){
                //遞迴呼叫
                reCopyFiles(s,t);
            }
        }//如果src是檔案
        else if (src.isFile()){
            InputStream in = null;
            OutputStream out = null;
            try {
                //建立輸入、輸出流拷貝檔案
                in = new FileInputStream(src);
                out = new FileOutputStream(target.getAbsoluteFile()+File.separator+src.getName());
                int len = -1;
                //每次寫8位元組
                byte[] bytes = new byte[1024*8];
                while ((len=in.read(bytes))!=-1){
                    out.write(bytes,0,len);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (in != null){
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out!=null){
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
}