Java: Copy Directory & Recursive Delete

Posted on

There are a few tasks that are not easily done in Java. Two of the ones that I encountered are to recursively copy a directory from one location to another and to recursively delete a directory. Oracle’s Java API provides a function to delete a directory but only when it is empty. A bit a annoying since most operating systems provide you with a command to recursively delete directories, why re-invent the wheel?

public void recursiveDelete(File rootDir) {
	recursiveDelete(rootDir, true);
}

public void recursiveDelete(File rootDir, boolean deleteRoot) {
	File[] childDirs = rootDir.listFiles();
	for(int i = 0; i < childDirs.length; i++) {
		if(childDirs[i].isFile()) {
			childDirs[i].delete();
		}
		else {
			recursiveDelete(childDirs[i], deleteRoot);
			childDirs[i].delete();
		}
	}
		
	if(deleteRoot) {
		rootDir.delete();
	}
}

Copying directories is another issue that is not supported in Java (at least until 1.6.x) It seems Java 7 has some support for this, though I have not tested it. Though you would still want some common code that would run on Java 5, 6, and 7 for backwards compatibility.

public void copyDirectory(File sourceLocation, File targetLocation) throws IOException {
	if(sourceLocation.isDirectory()) {
		if(!targetLocation.exists()) {
			targetLocation.mkdir();
		}

		String[] children = sourceLocation.list();
		for(int i = 0; i < children.length; i++) {
			copyDirectory(new File(sourceLocation, children[i]), new File(targetLocation, children[i]));
		}
	}
	else {
		InputStream in = new FileInputStream(sourceLocation);
		OutputStream out = new FileOutputStream(targetLocation);
		
		try {
			byte[] buf = new byte[1024];
			int len;
			while((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
		}
		finally {
			in.close();
			out.close();
		}
	}
}
Advertisements

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s