在各自岗位上尽职尽责,无需豪言壮语,默默行动会诠释一切。这世界,虽然没有绝对的公平,但是努力就会增加成功和变好的可能性!而这带着未知变量的可能性,就足以让我们普通人拼命去争取了。
欢迎来到~一支会记忆的笔~博客主页

java文件夹复制实例

java基础之-如何复制目录

 

在此示例中,我将d:\file下的所有子目录和文件复制到新位置d:\temp。如果要将目录及其包含的所有子文件夹和文件从一个位置复制到另一个位置,请使用下面的代码,该代码使用递归遍历目录结构,然后使用Files.copy()函数复制文件。

 public static void main(String[] args) {

        //源目录D:\file
        File sourceFolder = new File("d:\\file");

        //目标目录D:\temp
        File destinationFolder = new File("d:\\temp");

        //调用复制
        copyFolder(sourceFolder, destinationFolder);

    }
    private static void copyFolder(File sourceFolder, File destinationFolder) throws IOException
    {
        //Check if sourceFolder is a directory or file
        //If sourceFolder is file; then copy the file directly to new location
        if (sourceFolder.isDirectory())
        {
            //Verify if destinationFolder is already present; If not then create it
            if (!destinationFolder.exists())
            {
                destinationFolder.mkdir();
                System.out.println("Directory created :: " + destinationFolder);
            }

            //Get all files from source directory
            String[] files = sourceFolder.list()

            //Iterate over all files and copy them to destinationFolder one by one
            for (String file : files)
            {
                File srcFile = new File(sourceFolder, file);
                File destFile = new File(destinationFolder, file);

                //递归调用复制子目录
                copyFolder(srcFile, destFile);
            }
        }
        else
        {
            //使用文件复制工具进行复制
            Files.copy(sourceFolder.toPath(), destinationFolder.toPath(), StandardCopyOption.REPLACE_EXISTING);
            System.out.println("File copied :: " + destinationFolder);
        }
    }

 

结果如下:

 

 

 

 

提示:使用Files.copy()方法,可以复制目录。 但是,目录内的文件不会被复制,因此即使原始目录包含文件,新目录也为空。
同样,如果目标文件存在,则复制将失败,除非指定了REPLACE_EXISTING选项。

 

posted @ 2020-03-09 14:10  一支会记忆的笔  阅读(403)  评论(0编辑  收藏  举报
返回顶部
【学无止境❤️谦卑而行】