Watt
Watt

Reputation: 3164

How to merge two Folder files into one in Java

I am trying to create a simple function which copies or merge two or more folder files into one single folder.

I started with below. I thought to post here to get a better quality code.

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

When there is a conflict in file copying (i.e. file with same name exists on two or more folder) I want the file with latest timestamp get copied in mergedFolder.

Do you know the best way to merge two or more folders files into one?

Let me know if question is not clear.

Upvotes: 2

Views: 4473

Answers (2)

ShyJ
ShyJ

Reputation: 4640

You can create a Map<String, File> of the files you want to copy by traversing the merged dirs and keeping the newest files. Then you can copy the files you have in a map.

A sample code (haven't tried it) might look like this:

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;
}

Upvotes: 2

dacongy
dacongy

Reputation: 2552

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

To get timestamp, see File.lastModified()

Upvotes: 1

Related Questions