Tuesday, March 27, 2007

Java Tidbits - Copy file

I recently moved to a Java group in my company. One of the most important things for a programmer is a method to copy a file. Unfortunately Java does not have an API call to do it meaning i cannot call a FileHelper class and do a copy file.

One of the programs i found on the internet( with some of my modifications) was to use a buffered reader...here is the sample function

public static void copyFile(File src, File dst) throws IOException {
InputStream inputStream = null;
OutputStream outputStream = null;

try
{

inputStream = new BufferedInputStream(new FileInputStream(src));
outputStream = new BufferedOutputStream(new FileOutputStream(dst));

while (true)
{
int numofbytesread = inputStream.read();
if (numofbytesread == -1) break;
outputStream.write(numofbytesread);
}
}
finally
{
if (inputStream != null) inputStream.close();
if (outputStream !=null) outputStream.close();
}

}

A better and more efficient method would be to use File channels:

public static void copyFile(File src, File dst) throws IOException {
try
{
FileChannel sourceChannel = new FileInputStream(src).getChannel();
FileChannel destChannel = new FileOutputStream(dst).getChannel();
sourceChannel.transferTo( 0, sourceChannel.size(), destChannel );
sourceChannel.close();
destChannel.close();
}
catch (IOException e)
{
System.out.println("IO Exception occured while copying File. Stack Trace:");
e.printStackTrace();
}
}


Will update the blog with more Java tidbits as i learn something new.