Copy all files from Source to Destination Java

I have to code a java method public void public void copyTo(Path rSource, Path rDest) that copies all files from existing directory rSource to a new directory rDest with the same name. rSource must exist and rDest must not exist, runtime exception if not true. I can’t seem to make it work, help!

What I tried :

public void copyTo(Path rSource, Path rDest){
    if(!(Files.exists(rSource) && Files.isDirectory(rSource)) || (Files.exists(rDest))){
        throw new RuntimeException();
    }
    try {
        Files.createDirectory(rDest);
        if(Files.exists(rDest)){
            try(DirectoryStream<Path> stream = Files.newDirectoryStream(rSource)) {
                for(Path p : stream) {
                    System.out.println(p.toString());
                    Files.copy(p, rDest);
                }
            } catch( IOException ex) {
            }
        }
    } catch (IOException e) {
    }
}

Answer

Files.copy() at least takes two parameters, source and destination files path or stream. The problem in your case is that you are passing rDest folder Path, not the actual file Path. Just modify the code inside your for loop to append the files name from the source to the destination folder Path:

Path newFile = Paths.get(rDest.toString() + "/" + p.getFileName());
Files.copy(p, newFile);

Correct me if I’m wrong