user2406854 user2406854 - 1 month ago 4x
Java Question

How can I move a file to a non-empty directory?

I'm new to Java's nio package and I can't figure out how to get a file from one directory into another. My program is supposed to read through a directory and its subdirectories and process files based on certain conditions. I can get all the files using Files.walkFileTree but when I try to move them I get a java.nio.file.AccessDeniedException.

If I try to copy them, I get a DirectoryNotEmptyException. I haven't been able to find any help on Google. I'm sure there must an easy way to move a file from one directory to another, but I can't figure it out.

This is what I'm trying that gets the DirectoryNotEmptyException:

private static void findMatchingPdf(Path file, ArrayList cgbaFiles) {
Iterator iter = cgbaFiles.iterator();
String pdfOfFile = file.getFileName().toString().substring(0, file.getFileName().toString().length() - 5) + ".pdf";
while (iter.hasNext()){
Path cgbaFile = (Path);
if (cgbaFile.getFileName().toString().equals(pdfOfFile)) {
try {
Files.move(file, cgbaFile.getParent(), StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {

I'm iterating through a list of files, trying to match a .meta file with a .pdf of the same name. Once I find the match, I move the metadata file to the directory that has the pdf.

I get this exception:
java.nio.file.DirectoryNotEmptyException: C:\test\CGBA-RAC\Part-A
at sun.nio.fs.WindowsFileCopy.move(
at sun.nio.fs.WindowsFileSystemProvider.move(
at java.nio.file.Files.move(
at cgba.rac.errorprocessor.ErrorProcessor.findMatchingPdf(
at cgba.rac.errorprocessor.ErrorProcessor.matchErrorFile(
at cgba.rac.errorprocessor.ErrorProcessor.main(

Files.move(file, cgbaFile.getParent(), StandardCopyOption.REPLACE_EXISTING);

For the target, you're providing the directory you want to move the file into. This is incorrect. You need to specify the path to the file within the target directory.

For example, suppose you wanted to move /tmp/foo.txt to the /var/tmp directory. You're calling Files.move("/tmp/foo.txt", "/var/tmp") when you should be calling Files.move("/tmp/foo.txt", "/var/tmp/foo.txt").

You're getting that specific error because the JVM is trying to delete the target directory in order to replace it with the file.

One of these ought to generate the correct target path:

Path target = cgbaFile.resolveSibling(file.getFileName());

Path target = cgbaFile.getParent().resolve(file.getFileName());