Home > Software design >  How to copy specific files from one directory to another in Java
How to copy specific files from one directory to another in Java

Time:02-17

I have a directory with a bunch of files that i need to copy to another directory , Using Java i would only like to copy the files that end with a ".txt" extension. I'm familiar with doing it for one file as shown below , please could you help me do this as a loop to see which files in the source directory match with a "txt" extension and then copy them all over to a new directory.

File sourceFileLocation = new File(
                "C:\\Users\\mike\\data\\assets.txt");

        File newFileLocation = new File(
                "C:\\Users\\mike\\destination\\newFile.txt");
        try {
            Files.copy(sourceFileLocation.toPath(), newFileLocation.toPath());

        } catch (Exception e) {

            e.printStackTrace();
        }

CodePudding user response:

You can use Files#list(Path) to obtain a stream and use stream operations to filter and collect only those file names that contain the extension txt. For example:

List<Path> paths = Files.list(Paths.get("C:/Users/hecto/Documents")).filter(path -> path.toString().endsWith(".txt")).collect(Collectors.toList());
for (Path path : paths) {
    System.out.println(path.toString());
}

For me, this prints out:

C:\Users\hecto\Documents\file1.txt
C:\Users\hecto\Documents\file2.txt
C:\Users\hecto\Documents\file3.txt

Even though I have other files and folders in that directory enter image description here

Using that, I came up with this solution to copy over those filtered files from their current location to a new destination and preserving the original names (Using Java 8 or above):

try (Stream<Path> stream = Files.list(Paths.get("C:/Users/hecto/Documents"))) {
    List<Path> paths = stream.filter(path -> path.toString().endsWith(".txt")).collect(Collectors.toList());
    for (Path source : paths) {
        Path destination = Paths.get("C:/Users/hecto/Desktop/target"   File.separator   source.getFileName());
        Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
    }           
}

(Answer updated to use try-with-resources to close the stream)

  • Related