2

我正在尝试创建一个简单的函数,它将两个或多个文件夹文件复制或合并到一个文件夹中。

我从下面开始。我想在这里发布以获得更好质量的代码。

public  void copyDifferentFolderFilesIntoOne(String mergedFolderStr,String ... foldersStr)
{
  File mergedFolder= new File(mergedFolderStr);
  for(String folder: foldersStr)
  {
    //copy folder's files into mergedFolder
  }
}

当文件复制发生冲突时(即两个或多个文件夹上存在同名文件),我希望将具有最新时间戳的文件复制到mergedFolder中。

您知道将两个或多个文件夹文件合并为一个的最佳方法吗?

如果问题不清楚,请告诉我。

4

2 回答 2

2

您可以通过遍历合并的目录并保留最新文件来创建Map<String, File>要复制的文件。然后,您可以复制地图中的文件。

示例代码(尚未尝试过)可能如下所示:

public void copyDifferentFolderFilesIntoOne(String mergedFolderStr,
        String... foldersStr) {
    final File mergedFolder = new File(mergedFolderStr);
    final Map<String, File> filesMap = new HashMap<String, File> ();
    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;
}
于 2012-11-21T22:27:24.570 回答
1

To copy file, look at Standard concise way to copy a file in Java?

To get timestamp, see File.lastModified()

于 2012-11-21T22:17:01.380 回答