Saturday, October 1, 2011

Java : File copy program


Simple Java program to copy a file from its source to destination. Simply provide source file and a destination directory in the below function copyFunction(File srcFile,File destDirectory).


/* FileCopyProgram.java */
import java.io.*;
public class FileCopyProgram
{
public void copyFunction(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) 
{
FileCopyProgram cf = new FileCopyProgram();
cf.copyFunction(new File("C:\\Test\\Noname1.txt"),new File("D:\\Software"));
}
}

No comments:

Post a Comment