Friday, June 12, 2009

Copy, move and delete files using Java

Delete
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.

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

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

Copy

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)
                in.close();
            if (out != null)
                out.close();
        }
    }
}
The above example uses NIO API from Java 5, which finishes task pretty fast.

6 Comments: