124697
124697

Reputation: 21893

How can I copy a file and the directory structure where it exists?

I need to copy a File from A to B but keep the directory structure.

for example

C:\folder\second folder\myFile.txt
to 
C:\new folder\my second folder\myFile.txt

so that if I the new destination does not exists it will get created

I have tried this example but it copies the whole directory not just the file I specified.

Upvotes: 0

Views: 46

Answers (1)

Sage
Sage

Reputation: 15408

Make use of the File.mkdirs() function: Creates the directory named by this abstract pathname, including any necessary but nonexistent parent directories. Note that if this operation fails it may have succeeded in creating some of the necessary parent directories.

Prior to reading and writing the file, you can check whither the file path exists, if not then create it. For example:

 String s = "c:\\A Dir\\B Dir\\myFile.txt";
 File f = new File(s);
 if(!f.getParentFile().exists())         
      f.getParentFile().mkdirs(); // create the parent directory "c:\\A Dir\\B Dir\\"

Upvotes: 4

Related Questions