Jun 15, 2011

want to copy a dir (with files) to another directory ?


Hi Guys here is a piece of code used to copy a directory with files to another directory. It worked really well for me. There are more different methods to copy a dir to new dir. All I have done is first copied the names of all files in the original dir into a "list" and then by using those names i looped through one by one and created a new file object using those same file names then wrote all those files as bytes into the newly created files.


     String files="";
 List allFiles = new ArrayList();
 File folder = new File("C:/my files/files");
 File[] listOfFiles = folder.listFiles();
 for (int i = 0; i < listOfFiles.length; i++){
 if (listOfFiles[i].isFile()){
          files = listOfFiles[i].getName();
          allFiles.add(files);
File f1 = new File("C:/my files/"+files);
File f2 = new File("C:/new my files/"+files);
InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0){
out.write(buf, 0, len);
}
in.close();
out.close();
      }
 }

hope this helps.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home