How to rename a folder containing files

How do I rename a folder which contains files? The function moveFileTo says it can be used to move or rename a file, but will calling that on a folder (that contains files) work? Would I make a File object using the old path, then call this with the new path, and it will just work?

(Also, I am assuming that any File objects I am holding onto that reference the files inside the original folder will need to be re-created using their new path, right?)

Or, would it be better/simpler/safer to create the new folder, copy the Files I have in the old folder to the new folder, and then delete the old folder?

I’ve always thought that moving files around for a simple rename is wrong. Imagine you have a 4 GB file you need to rename. Instead of using the OS rename function, it copies the entire 4 GB file under the new name and then deletes the old file.

It has very bad performance, is bad for SSD write-cycles, and needs twice the storage space. Imagine multi-TB files rename. Shudder.

Calling the win32 “_wrename” function takes a couple of milliseconds, doesn’t copy anything anywhere, and can do files AND folders.

The exact same function “rename” also exists for POSIX systems.

Agreed. But does that function allow renaming folders, even if they contain files currently? It makes no explicit mention of folders.

From the win32 rename documentation:

The rename function renames the file or directory specified by oldname to the name given by newname . The old name must be the path of an existing file or directory. The new name must not be the name of an existing file or directory. You can use rename to move a file from one directory or device to another by giving a different path in the newname argument. However, you cannot use rename to move a directory. Directories can be renamed, but not moved.

So yes, you can rename folders/directories with it and it doesn’t matter if they are empty or not.

Have you tried it? I would expect it to work. Moving within one filesystem is just changing the FAT or whatever table it uses. Moving to a different filesystem will do a copy and delete the original afterwards, as it needs to be able to roll back if the operation failed.

Yep, seems to work (once I worked out the extraction of the old folder name and replacement with the new one in the path string).

(If the documentation for that function was explicit that this works with folders as well as files, that would have saved me some time.)

Now I need to figure out how to update the File objects that I have for each of the files that are within that folder. (Along with re-creating any FileInputStream and AudioFormatReader object(s) I may have already created for accessing them?)