Copying multiple files from one folder to another in JAVA 15

168 Views Asked by At
    Path src = Paths.get("./resources");
    Path dst = Paths.get("./trash");
    
    try {
        
        DirectoryStream<Path> ds = Files.newDirectoryStream(src);
            
        for(Path fileorDir : ds) {
            System.out.println(fileorDir);
            Files.copy(fileorDir, dst);
        }
    }catch(IOException ioe){
        ioe.printStackTrace();
    }

//The error im getting is java.nio.file.FileAlreadyExistsException so from what i understand its trying to save the file to that exact location, not inside it, i need to save a couple text files this way, if i change the destination address to say trash/trash.txt it will save a file there called trash.txt. but then on the next loop of the for each it throws a "Already exists" exception...

Can somebody explain how i can just save all txt files into that folder from the src folder, as if dragging and dropping them?

Many thanks

1

There are 1 best solutions below

5
On

You can use a option in copy() who is StandardCopyOption.REPLACE_EXISTING but the problem is that dst isn't the good path. For exemple, ressources/trash.txt should be copy in trash/trash.txt but dst is just /trash like path. Sorry for my english and it's my first answer :) Be merciful .