Has anyone got any clever tricks for determining the size of the contents of a directory without doing the obvious (descend recursively and count bytes)?
I'm trying to make a progress bar happen for a recursive descend-read-and-load of a directory, and it would be cool if I could track it by bytes read, but doing two descents of the same directory seems a little wrong to me. ("Yo, dawg, I heard you like recursive descent, so I put a recursive descent on your recursive descent so you can recursively descend before you recursively descend" :) )

I've got something that works, based on subdividing the amount to complete and passing that percentage to the next recursion, but obviously that tends to stick a little when I get five levels down and the percentage assigned to each file gets miniscule. Updating the progress bar by bytes would avoid that problem and make the progress look smoother, if I could get the total byte count of the directory. Unfortunately, File.length() is undefined for directories - any other brilliant ideas?

EDIT: re-reading this, I see that the thread title is not very accurate. Oh, well

come on it is not that complicated to make it recursive in a single loop

static long getDirSize(File dir) {
		if (dir.isFile()) 
			return  dir.length();

		File[] subFiles = dir.listFiles();

		long size = 0;
		for (File file : subFiles) {
			if (file.isFile())
				size += file.length();
			else 
				size += getDirSize(file);
		}

		return size;
	}

Oh I know how to do it recursively - it's just that I don't want to load in more processing and slow things down. It's a pretty deep directory, and it's already taking about two minutes to read everything.
If there's no way to get the filesystem to tell me, I'll just go ahead with the per-file method, it's working okay. The other way would just be hipper, is all. :)

"If there's no way to get the filesystem to tell me"
Not really in Java as it is OS and so File System independant
On Unix you can getTotalSpace() and getUsableSpace() on a partition

commented: Thanks for your help. +2

Nuts. This is immediately destined for Windows deployments, but I'd like to make it system-independent, since I think others might have a use for it as well.
No worry, though, my current solution is working okay. Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.