Java directory copy

Directory copy

import java.io.*;

/**
 * 目录拷贝
 */
public class CopyAll {
    public static void main(String[] args) {

        File srcFile = new File("D:\\StudySource\\Java\\powernode\\文本笔记");

        File destFile = new File("F:\\Java 目录拷贝\\");

        copyAll(srcFile, destFile);
    }

    private static void copyAll(File srcFile, File destFile) {

        if (srcFile.isFile()) {

            // 是文件,递归结束,开始拷贝
            FileInputStream in = null;
            FileOutputStream out = null;

            try {
//                in = new FileInputStream(srcFile.getAbsoluteFile());
                // 或者这么写
                in = new FileInputStream(srcFile);

                byte[] bytes = new byte[1024 * 1024];

                out = new FileOutputStream((destFile.getAbsolutePath().endsWith("\\") ?
                        destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\" )
                        + srcFile.getAbsolutePath().substring(3));

                int readCount = 0;

                while((readCount = in.read(bytes)) != -1){
                    out.write(bytes,0, readCount);
                }
                out.flush();

            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (in == null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return;
        }

        File[] files = srcFile.listFiles();
        // 如果是目录,则需要对应新建目录

        for (File f : files) {

            if (f.isDirectory()){

                String srcDir = f.getAbsolutePath();    // 原文件绝对路径

                String srcDir2 = srcDir.substring(3);   //截掉前面的盘符

                // 这里是因为有时候复制到 F:\\ 和 F:\\a\\b\\ 下读取的绝对路径不一样
                String destDir = (destFile.getAbsolutePath().endsWith("\\") ?
                                    destFile.getAbsolutePath() : destFile.getAbsolutePath() + "\\" )
                                    + srcDir2;

                // 新建一个 File 对象
                File newFile = new File(destDir);

                // 目录不存在,则以多重目录的方式新建目录
                if (!newFile.exists()){
                    newFile.mkdirs();
                }
            }
            // 递归
            copyAll(f, destFile);
        }
    }
}

Guess you like

Origin www.cnblogs.com/yerun/p/12687249.html