Friday, December 25, 2009

Java : Copy source file to destination directory

This is simple java program to copy a particular source file to destination directory. Just provide a source file (file which is to copy) and provide a destination directory where to file to be coppied, lets look at the code

/* CopyFile.java */

import java.io.*;

public class CopyFile
{
public void copy(File srcFile,File destDirectory)
{
try
{
String srcFilePath = srcFile.getPath();

String fileName = srcFilePath.substring(srcFilePath.lastIndexOf("\\")+1);

File destFile = new File(destDirectory.getPath()+"\\"+fileName);

InputStream inSrc = new FileInputStream(srcFile);

OutputStream outDest = new FileOutputStream(destFile);

byte[] buffer = new byte[4096];
int bytesRead;

while ((bytesRead = inSrc.read(buffer)) > 0)
{
outDest.write(buffer, 0, bytesRead);
}

inSrc.close();
outDest.close();

System.out.println("File copy sucessfully : "+fileName);
}
catch (IOException ex)
{
System.out.println("Exception in copy : "+ex);
}
}

public static void main(String[] args)
{
CopyFile cf = new CopyFile();

cf.copy(new File("C:\\Downloads\\Test.zip"),new File("D:\\Work\\Files"));
}
}

No comments:

Post a Comment