Friday, June 12, 2009

Copy, move and delete files using Java

Deleting files in Java is fairly simple, just one method call-

   new File("file path").delete();

Only caveat here is that 'non-empty' directories can not be deleted. Of course you will need to have write permission (required for all write operations on file) on that directory as well.

Moving files is also as simple as deleting, just one method call-

   new File("source file path").renameTo(new File("destination file path"));


Copying files in Java needs some heavy lifting as there is no API to do this task. Here is an example to copy files from one directory to another-

public void copyFiles(String source, String destination) throws IOException {
    File srcDir = new File(source);
    File[] files = srcDir.listFiles();

    FileChannel in = null;
    FileChannel out = null;
    for (File file : files) {
        try {
            in = new FileInputStream(file).getChannel();
            File outFile = new File(destination, file.getName());
            out = new FileOutputStream(outFile).getChannel();
            in.transferTo(0, in.size(), out);
        } finally {
            if (in != null)
            if (out != null)
The above example uses NIO API from Java 5, which finishes task pretty fast.