Link to home
Start Free TrialLog in
Avatar of codechewer
codechewer

asked on

copying a folder and its contents(subfolders and files) from one location to another

Hi Experts,

I'm trying to copy a folder containing several files and subfolders which also contain files and subfolders, etc... I don't know the names of the subfolders nor the files.

I would like to copy this main folder (c:\myfolder) to another location (c:\test\myfolder) with all its content. How do I achieve this. i havn't as yet found a way of copying a folder and its contents in java.



Thank you for your time,

codechewer
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Might be easiest to Runtime.exec("xcopy...
Avatar of codechewer
codechewer

ASKER

thanks CEHJ. that was really helpfull but my environment takes the api as Runtime.getRuntime().exec("xcopy...

i have tried it with dir, mkdir which runs perfectly on the commandline but throws and exception as

CreateProcess: mkdir myfoldername  error:  2

where mkdir myfoldername is a commandline command.

usign jbuilder 6 and tomcat 4.1.24

be most grateful to here from you.
why don't you try this:

public static void copyDirectory(File aSourceDirectory, File aDestinationDirectory) throws IOException {
    int i;
    File sourceFile;
    File destinationFile;
    File[] files = aSourceDirectory.listFiles();

    if (!aDestinationDirectory.exists())
      aDestinationDirectory.mkdirs();

    for (i=0; i<files.length; i++) {
      sourceFile = files[i];
      destinationFile=new File(aDestinationDirectory, sourceFile.getName());
      if (sourceFile.isDirectory()) {
        if (!destinationFile.exists())
          destinationFile.mkdir();
        copyDirectory(sourceFile, destinationFile);
      }
      else {
        copyFile(sourceFile, destinationFile);
      }
   }
}

cheers,
  bruno
ASKER CERTIFIED SOLUTION
Avatar of brunomsilva
brunomsilva

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sorry - those command are shell commands so it would have to be:

Runtime.getRuntime().exec("cmd.exe dir ...