Some more java code here!!This would help you copy a folder from one place to another.It could help in various situations, this process could be automated as well.This code works with sub folders as well, so anything inside the folder is copied.Here's the code

import java.io.*;

public class CopyDirectory{

public static void main(String[] args) throws IOException{

CopyDirectory cd = new CopyDirectory();
BufferedReader in = new BufferedReader
(
new InputStreamReader(System.in));
System.out.println("Enter the source directory or file name : ");

String source = in.readLine();

File src = new File(source);

System.out.println("Enter the destination
directory or file name : "
);
String destination = in.readLine();

File dst = new File(destination);

cd.copyDirectory(src, dst);

}


public void copyDirectory(File srcPath, File dstPath)
throws IOException{

if (srcPath.isDirectory()){

if (!dstPath.exists()){

dstPath.mkdir();

}


String files[] = srcPath.list();

for(int i = 0; i <>){
copyDirectory(new File(srcPath, files[i]),
new File(dstPath, files[i]));

}

}

else{

if(!srcPath.exists()){

System.out.println("File or directory does not exist.");

System.exit(0);

}

else


{

InputStream in = new FileInputStream(srcPath);
OutputStream out = new FileOutputStream(dstPath);
// Transfer bytes from in to out
byte[] buf = new byte[1024];

int len;

while ((len = in.read(buf)) > 0) {

out.write(buf, 0, len);

}

in.close();

out.close();

}

}

System.out.println("Directory copied.");

}

}

4 comments

Anonymous said... @ January 18, 2009 at 10:15 PM

Can we copy pdf's from one place to another, also in batches thru Java???

Anonymous said... @ January 19, 2009 at 2:11 AM

Yea , you can copy any type of file , you can schedule it too , maybe using the Thread.Sleep Function . YOu can tell it to copy say once in few minutes or however else you need it!!

Anonymous said... @ March 15, 2013 at 8:25 AM

I think the "copyDirectory" method is better if static...
good code, thanks.

Unknown said... @ July 2, 2013 at 11:28 AM

whats < > in for loop???

Post a Comment