Does Files.copy(Path,Path) create directories?

knowads picture knowads · Apr 13, 2015 · Viewed 17.9k times · Source

I have a bunch of text files(say ss1.txt,ss2.txt,ss3.txt etc.) under a directory with my Java program (C:/Users/java/dir1)?
I want to move my txt files to a new directory that hasn't been created yet. I have a String address for all of my files and I think I can turn them into Paths using

Path path = Paths.get(textPath);

Would creating a String (C:/Users/java/dir2), turning that into a path using the above method and then using

Files.copy(C:/Users/java/dir1/ss1.txt,C:/Users/java/dir2)

result in ss1.text being copied to a new directory?

Answer

Daniel De León picture Daniel De León · Apr 30, 2019

This is very easy with Files.createDirectories()

Path source = Path.of("c:/dir/dir-x/file.ext");
Path target = Path.of("c:/target-dir/dir-y/target-file.ext");
Files.createDirectories(target.getParent());
Files.copy(path, target, StandardCopyOption.REPLACE_EXISTING);    

And do not worry if the directories already exist, in that case it will do nothing and keep going...