Saturday, August 27, 2011

Copying files in Java


This is something I've never really done much of, but when I've seen snippets of code which do this I've always thought how ugly and cumbersome it looks:

    File srcFile = new File(sourceFilePath);
    File destFile = new File(destinationFilePath);
    FileInputStream in = new FileInputStream(srcFile);
    FileOutputStream out = new FileOutputStream(destFile);
    byte[] buf = new byte[2048];
    int len;
    while ((len = in.read(buf)) > 0)
    {
        try
        {
   out.write(buf, 0, len);
}
catch (Exception e)
{
}
    }
    out.flush();
    in.close();
    out.close();

etc...

But there is now, at last, an easier way:

    import java.nio.channels.FileChannel;
    ...
    File srcFile = new File(sourceFilePath);
    File destFile = new File(destinationFilePath);
    FileInputStream in = new FileInputStream(srcFile);
    FileOutputStream out = new FileOutputStream(destFile);
    FileChannel srcFileChannel = in.getChannel();
    FileChannel destFileChannel = out.getChannel();

    destFileChannel.transferFrom(srcFileChannel, 0, srcFileChannel.size());
    srcFileChannel.close();
    destFileChannel.close();
   ...

No comments:

Post a Comment