Rename non empty directory issue using Java NIO

Viewed 1074

According to: How do I rename (not move) a file in JDK7?

I'm trying to rename folder name of not empty folder with java NIO

My result , is new directory created without files inside and not delete old one.

The code i used but it doesn't work:

  try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
      Path oldPath = fs.getPath("/some/directory2");
      Files.move(oldPath, oldPath.resolve("/some/directory_replaced2_2"), StandardCopyOption.REPLACE_EXISTING);
 } catch (IOException e) {
            e.printStackTrace();
        }

What I'm missing ? ( I want only rename folder)

1 Answers

You can rename directory using java.nio.file.Files.move method and then copy the files with Files.walkFileTree:

To move a file tree may involve copying rather than moving directories and this can be done using the copy method in conjunction with the Files.walkFileTree utility method.

You can follow java tutorial:

import static java.nio.file.StandardCopyOption.*;

Files.move(source, target, REPLACE_EXISTING);

the method is most often used with the file tree recursion mechanism. For more information, see Walking the File Tree.

Related