Noah Waldner
Noah Waldner

Reputation: 21

Copy Contents of a Directory with Java

In my Java program I have 2 paths (Strings) of 2 different directories.

I want a method to copy all the files from one directory to the other. (just the contents, not the folder).

How can I do that?

Upvotes: 0

Views: 67

Answers (2)

Ram Ghadiyaram
Ram Ghadiyaram

Reputation: 29237

Can use

org.apache.commons.io.FileUtils;

Collection getAllFilesThatMatchFilenameExtension(String directoryName, String extension)
{
  File directory = new File(directoryName);
  return FileUtils.listFiles(directory, new WildcardFileFilter(extension), null);
}

loop through the collection and call

   FileUtils.copyFileToDirectory(file, destinationDir);

Upvotes: 0

user3719857
user3719857

Reputation: 1123

Make a class that extends SimpleFileVisitor<Path> and override its methods. visitFile should copy the file to the new directory and the VisitDirectory methods should just continue down the tree. Then use the new class with Files.walkFileTree.

Upvotes: 1

Related Questions