2

我有大约 15 个文件夹。每个文件夹都有类似的子结构。我要合并文件夹的内容: 1. 一次取 2 个文件夹 2. 一次取 3 个文件夹 这样就可以保存两个同名的文件。

例子:

folder 1 
---pqr
------abc.txt
------xyz.txt

folder 2
---pqr
------abc.txt

合并后:

folder 3
---pqr
-------abc.txt
-------abc.txt(2)
-------xyz.txt

请帮我写一个java代码。提前致谢。

这就是我迄今为止在netbeans中所做的。

package merger;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class Merger {

    public static void main(String[] args)
    {

    }

    public void copyDifferentFolderFilesIntoOne(String mergedFolderStr,
            String... foldersStr) throws IOException
    {

        final File mergedFolder = new File(mergedFolderStr);
        final Map<String, File> filesMap = new HashMap<> ();
        for (String folder : foldersStr) {
            updateFilesMap(new File (folder), filesMap, null);
        }

        for (final Map.Entry<String, File> fileEntry : filesMap.entrySet()) {
            final String relativeName = fileEntry.getKey();
            final File srcFile = fileEntry.getValue();
            FileUtils.copyFile (srcFile, new File (mergedFolder, relativeName));
        }
    }

    private void updateFilesMap(final File baseFolder, final Map<String, File> filesMap,
            final String relativeName)
    {
        for (final File file : baseFolder.listFiles()) {
            final String fileRelativeName = getFileRelativeName (relativeName, file.getName());

            if (file.isDirectory())
            {           
                updateFilesMap(file, filesMap, fileRelativeName);
            }
            else {
                final File existingFile = filesMap.get (fileRelativeName);
                if (existingFile == null || file.lastModified() > existingFile.lastModified() ) {
                    filesMap.put (fileRelativeName, file);
                }
            }
        }
    }

    private String getFileRelativeName(final String baseName, final String fileName)
    {
        return baseName == null ? fileName : baseName + "/" + fileName;
    }    
}
4

0 回答 0