4

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)

Zabuzard
  • 25,064
  • 8
  • 58
  • 82
VitalyT
  • 1,671
  • 3
  • 21
  • 49
  • that's interesting, if I simply do `Path oldPath = Paths.get("/Users/me/Desktop/Folder"); Files.move(oldPath, oldPath.resolve("/Users/me/Desktop/Folder2"), StandardCopyOption.REPLACE_EXISTING);` this works just fine – Eugene Aug 29 '18 at 11:32
  • add inside /Users/me/Desktop/Folder , other files... – VitalyT Aug 29 '18 at 11:33
  • that's right, that folder is not empty, it has files and sub-folders with files – Eugene Aug 29 '18 at 11:34
  • how do you initialize the FileSystem uri , FileSystems.newFileSystem(uri,env) ? – VitalyT Aug 29 '18 at 11:43
  • look at my example *again*. I don't initialize that, since I don't need to – Eugene Aug 29 '18 at 11:43
  • Sorry , I'll update my question , cause i thought that is not important...i'm working with ZIP content and using FileSystem...in this case it is not working... – VitalyT Aug 29 '18 at 11:53
  • Do not edit your question in a way that invalidates existing answers. Instead, post a new question, thanks. Reverted the edit. – Zabuzard Nov 19 '19 at 18:06

1 Answers1

3

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.

Community
  • 1
  • 1
Ori Marko
  • 56,308
  • 23
  • 131
  • 233