java 实现文件/文件夹复制、删除、移动(二)

复制文件夹

View Code
 /**
     * <一句话功能简述>复制文件夹 <功能详细描述>
     * 
     * @param srcDir 文件夹的绝对路径
     * @param destDir 目标绝对路径
     * @throws Exception
     * @see [类、类#方法、类#成员]
     */
    public static void copyFolder(String srcDir, String destDir) throws Exception
    {
        File srcFile = new File(srcDir);

        // 在目标路径建立文件夹
        String name = srcFile.getName();
        File destFile = new File(destDir + File.separator + name);
        if (!destFile.exists())
        {
            destFile.mkdir();
        }

        if (srcFile.exists() && destFile.isDirectory())
        {
            File[] files = srcFile.listFiles();

            String src = srcDir;
            String dest = destFile.getAbsolutePath();

            for (File temp : files)
            {
                // 复制目录
                if (temp.isDirectory())
                {
                    String tempSrc = src + File.separator + temp.getName();
                    String tempDest = dest + File.separator + temp.getName();
                    File tempFile = new File(tempDest);
                    tempFile.mkdir();
                    
                    // 当子目录不为空时
                    if (temp.listFiles().length != 0)
                    {
                        // 递归调用
                        copyFolder(tempSrc, tempDest);
                    }
                }
                else
                // 复制文件
                {
                    String tempPath = src + File.separator + temp.getName();
                    copyFile(tempPath, dest);
                }
            }
        }
    }

 再写个删除就下班喽……请各位拍砖哦!

View Code
 /**
     * 删除文件夹 <功能详细描述>
     * 要先删除子内容,再删除父内容
     * @param dirPath 要删除的文件夹
     * @see [类、类#方法、类#成员]
     */
    public static void deleteFolder(String dirPath)
    {
        File folder = new File(dirPath);
        File[] files = folder.listFiles();
        
        for (File file : files)
        {
            if (file.isDirectory())
            {
                String tempFilePath = dirPath + File.separator + file.getName();
                deleteFolder(tempFilePath);
            }
            else
            {
                file.delete();
            }
            
        }
        
        folder.delete();
    }

 移动,剪切,其实也就是copy与delete的结合操作。

原文地址:https://www.cnblogs.com/guoyuqiangf8/p/2779606.html