简体   繁体   English

如何将目录文件夹复制到java中指定文件夹以外的子目录中?

[英]How to Copy directory folder to with in sub directory except specified folder in java?

I want to move parent folder subfolders to another parent subfolder using java,below is the folder structure.我想使用 java 将父文件夹子文件夹移动到另一个父子文件夹,下面是文件夹结构。

Source Dir : C:\Users\xxxxx\git\project\Parent
Desctinaton Dir: C:\Users\xxxxx\git\project\Parent\oldParent

Parent
       oldParent
Subdolder1
Subfolder2

Now i want to move Subfolder1,2 into oldParent folder.I'm using below code to move but it is not working现在我想将 Subfolder1,2 移动到 oldParent 文件夹中。我正在使用下面的代码来移动,但它不起作用

import org.apache.commons.io.FileUtils;
    public static void move(File sourceDir,File destinationDir){
            
            try {
               // FileUtils.copyDirectory(sourceDir, destinationDir);
                FileUtils.moveDirectory(sourceDir, destinationDir);
            } catch (IOException e) {
                e.printStackTrace();
            }
            
        }

Exception:例外:

org.apache.commons.io.FileExistsException: Destination C:\Users\xxxxx\git\project\Parent\oldParent already exists

I've modified little bit code,just added and after moving files,not deleting the files,then i've used below code,Now it is moving the folders and deleting the folders after move.我修改了一点代码,只是在移动文件后添加,而不是删除文件,然后我使用了下面的代码,现在它正在移动文件夹并在移动后删除文件夹。

import org.apache.commons.io.FileUtils;
 public static void moveDirectory(File sourceDir, File destinationDir) throws IOException {
        FileUtils.copyDirectory(sourceDir, destinationDir);

try {

            File directory = new File(sourceDir);
            File[] subdirs = directory.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY);
            for (File dir : subdirs) {
                // System.out.println("Directory: " + dir.getName());
                String name = dir.getName();
                if (!name.equalsIgnoreCase(folderName)) {
                    FileUtils.forceDelete(new File(folderPath + name));
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM