Skip to content
Advertisement

Moving files from one directory to another with Java NIO

I am using the NIO libraries but I am getting a strange error when I try to move files from one directory to another.

JavaScript

Iterate over elements that start with “2014” and move them in the new directory (newDir, which is also called 2014)

JavaScript

I get the java.nio.file.FileAlreadyExistsException because my folder (2014) already exists. What I actually want to do is move all the files that start with “2014” INSIDE the 2014 directory.

Advertisement

Answer

Files.move is not equivalent to the mv command. It won’t detect that the destination is a directory and move files into there.

You have to construct the full destination path, file by file. If you want to copy /src/a.txt to /dest/2014/, the destination path needs to be /dest/2014/a.txt.

You may want to do something like this:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement