Macro: Move ("cut and paste") directories including all subfolders and files


#1

Hi,

I would like to move some directories (including all subfolders and files) after applying an ImageJ macro, but the documented “File.rename(path1, path2)” doesn’t work. Basically, I just want “cut and paste” the whole directory.

Does anyone know a simple solution for that?

Thanks in advance!


#2

Hi.
What do you mean by “does not work”?

Similarly, would it be possible to directly save your data in the final folder rather than having to move the data around?

Best


#3

Hi,

“File.rename(path1, path2) - Renames, or moves, a file or directory. Returns “1” (true) if successful.”

For me, it always returns 0 and doesn’t move the directory or any of the files. It just works for individual files, but not for the whole directory (if path1 is a single file).

Unfortunately, it’s not an option to directly save my data already in the final folder.

Best


#4

I’ve tested this on a folder with subfolders and plenty of images and it works as advertised (In win10)


path1 = "D:/Data Location 1/"; // Has subfolders, zip files, images
path2 = "D:/New Location/"; // does not exist

File.rename(path1, path2);
// New Location has everything and Data Location 1 no longer exists...
//returns 1

Could you paste the macro code that runs this? It could be that there is a problem with the path you’re passing that is invalid somehow…


#5

I just tested it again, but this time path2 also is on the local computer and it worked.

Before, path2 was a mapped network drive and I actually want to move the files there. Just changing from “D:/…” to “X:/…” seems to be the reason why it’s not working. Again, individual files DO WORK, also for moving them to the mapped network drive.


#6

Yup it seems the underlying fuctions fail when changing filesystems.
I read the comments in

Are you on windows? then perhaps you can do something like calling the windows native robocopy command and this works for me to and from our server

sep = File.separator;
path1 = "D:"+sep+"Data Location 1"+sep; // Has subfolders, zip files, images
path2 = "Z:"+sep+"New Location"+sep; // does not exist

File.rename(path1, path2);
exec("robocopy", path1, path2, "/E");

Because moving files like this NEEDS to involve a copy step, you can execute this and then just delete the original folder with. [EDIT: The previous version was wrong, I modified it to actually work: :slight_smile: )]

exec("cmd", "/c", "del", path1, "/Q", "/F");

exec("cmd", "/c", "rmdir", path1, "/Q", "/S");

And I would like to add the disclaimer that you should be very careful with that kind of command, as if you give it a wrong folder, you will silently destroy your system or data :slight_smile:


#7

Thank you for your help! It works perfectly.