簡體   English   中英

合並目錄 - Java

[英]Merge directories - Java

我有一個目錄:

| content
| - folderWithTextFile
| - - textFile.txt
| - - folderWithPdfFile
| - - - pdfFile.pdf

...我想將它合並到另一個同名目錄中:

| content
| - folderWithExeFile
| - - exeFile.exe
| - - folderWithPngFile
| - - - pngFile.png

...所以我最終得到了這個:

| content
| - folderWithTextFile
| - - textFile.txt
| - - folderWithPdfFile
| - - - pdfFile.pdf
| - folderWithExeFile
| - - exeFile.exe
| - - folderWithPngFile
| - - - pngFile.png

使用Files.move(target, destination, StandardCopyOptions.REPLACE_EXISTING)會給我一個DirectoryNotEmptyException因為secondFolder不為空。

使用 Apache Commons IO FileUtils.moveDirectory FileUtils.moveDirectory(target, destination)會給出FileExistsException ,因為目標已經存在。

我想要一種合並這兩個結構的方法。 它必須復制整個結構,而不僅僅是一個文件。

這是一種合並兩個目錄的方法。 第二個參數的目錄會移動到第一個,包括文件和目錄。

import java.io.File;
         
        public class MergeTwoDirectories {
            public static void main(String[] args){
                String sourceDir1Path = "/home/folderWithTextFile/textFile.txt";
                String sourceDir2Path = "/home/folderWithTextFile/exeFile.exe";
         
                File dir1 = new File(sourceDir1Path);
                File dir2 = new File(sourceDir2Path);
         
                mergeTwoDirectories(dir1, dir2);
         
            }
         
            public static void mergeTwoDirectories(File dir1, File dir2){
                String targetDirPath = dir1.getAbsolutePath();
                File[] files = dir2.listFiles();
                for (File file : files) {
                    file.renameTo(new File(targetDirPath+File.separator+file.getName()));
                    System.out.println(file.getName() + " is moved!");
                }
            }
        }

我想出了這個解決方案:

private static void moveDirectory(File parentFrom, File parentTo) {
        log("Moving " + parentFrom.toPath() + " to " + parentTo);

        for (File file : parentFrom.listFiles()) {

            // Is a regular file?
            if (!file.isDirectory()) { // Is a regular file
                File newName = new File(parentTo, file.getName());
                file.renameTo(newName);
                log("Moved " + file.getAbsolutePath() + " to " + newName.getAbsolutePath());
            } else { // Is a directory
                File newName = new File(parentTo, file.getName());
                newName.mkdirs();
                log("Moving dir " + file.getAbsolutePath() + " to " + newName.getAbsolutePath());
                moveDirectory(file, newName);
            }

            file.delete();
        }

        parentFrom.delete();
    }

它遞歸地將輸入文件的內容復制到 output 文件,並清理輸入。 它效率低下,絕對不理想,但它適用於我的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM