Java如何复制目录_Java基础教程系列

Java如何复制目录_Java基础教程系列

文件夹复制实例

在此示例中,我将c:\temp下的所有子目录和文件复制到新位置c:\tempNew。

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
 
public class DirectoryCopyExample
{
    public static void main(String[] args) throws IOException
    {
        //源目录
        File sourceFolder = new File("c:\\temp");
         
        //目标目录
        File destinationFolder = new File("c:\\tempNew");
 
        //调用复制
        copyFolder(sourceFolder, destinationFolder);
    }
    /**
     * 此功能以递归方式将所有子文件夹和文件从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);
        }
    }
}

上方代码运行结果:

Directory created :: c:\tempNew
File copied :: c:\tempNew\testcopied.txt
File copied :: c:\tempNew\testoriginal.txt
File copied :: c:\tempNew\testOut.txt

 

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

 

Java如何复制目录_Java基础教程系列

相关文章:

你感兴趣的文章:

标签云: