Cesar
Cesar

Reputation: 115

Copying files from one directory to another in java throws NoSuchFileException

I have a HashSet of Strings, which are names of files that I want to copy from the working direcorory to the "path" directory. I find that the following piece of code should be working, however, I get a java.nio.file.NoSuchFileException: /commits/1/hello.txt exception.

  Hashset<String> stagedQueue = HashSet<String>();
    stagedQueue.put("hello.txt");
    stagedQueue.put("bye.txt");


String path = "/commits/" + commitID;

                for (String file : stagedQueue) {
                    Files.copy((new File(file).toPath()), 
                        (new File(path + "/" + file).toPath()));

What can I do to fix this? I can't figure out why I am getting these exceptions. Please note that I am moving these into an empty directory.

Upvotes: 0

Views: 522

Answers (1)

fge
fge

Reputation: 121820

Don't go through File; you use java.nio.file.

Your problem here is that you try and copy your initial file into a directory which does not exist yet:

String path = "/commits/" + commitID;

First of all, this is the destination directory, so call it dstdir, for instance. Then create the base directory and copy the files into it:

final Path basedir = Paths.get("/commits", commitId);

Files.createDirectories(basedir);

for (final String file: baseQueue)
    Files.copy(Paths.get(file), basedir.resolve(file));

Upvotes: 1

Related Questions