Saturday, January 24, 2009

Java : Simple program to copy Directory (subdirectories and files) from specified source to specified destination.

Here is the code of the program :




import java.io.*;
import java.text.SimpleDateFormat;

public class DirectoryCopier
{
public static void main(String[] args) throws IOException
{
//Creating instance of DirectoryCopier
DirectoryCopier cd = new DirectoryCopier();

//Specifying Source Directory
String source = "D:\\Blog";

//Creating File of source directory
File src = new File(source);

//Specifying Destination Directory
String destination = "C:\\copyOfBlog";

File dst = new File(destination);

//Calling method DirectoryCopier with source and destination
cd.DirectoryCopier(src, dst);
}

public void DirectoryCopier(File srcPath, File dstPath) throws IOException
{
//If Source is a Directory
if (srcPath.isDirectory())
{
System.out.println(srcPath + "is directory.");

//If Destination directory not exists, create it
if (!dstPath.exists())
{
System.out.println("calling mkdir " + dstPath);
dstPath.mkdir();
}

//Get All Available Files in this source directory
String files[] = srcPath.list();

//Iterate each file
for(int i = 0; i < files.length; i++)
{
System.out.println("--Source "+srcPath);
System.out.println("--Destination "+dstPath);

//Recursively calling DirectoryCopier
DirectoryCopier(new File(srcPath, files[i]),new File(dstPath, files[i]));
}
}
//If Source is a leaf node
else
{
//If Source does not exists print it and exit
if(!srcPath.exists())
{
System.out.println("File or directory does not exist.");
System.exit(0);
}
else
{
System.out.println("Source "+srcPath);
System.out.println("Destination "+dstPath);

//Copying by bytes
FileInputStream in = new FileInputStream(srcPath);
FileOutputStream 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.");
}
}