I need to find the total size of a drive in Java 5 (or 1.5, whatever). I know that Java 6 has a new method in java.io.File, but I need it to work in Java 5.
Apache Commons IO has org.apache.commons.io.FileSystemUtils to provide the free disk space, but not the total disk space.
I realize this is OS dependant and will need to depend on messy command line invocation. I’m fine with it working on “most” systems, i.e. windows/linux/macosx. Preferably I’d like to use an existing library rather than write my own variants.
Any thoughts? Thanks.
Update:
I apologise for misreading the question, I recommend copying the FileSystemUtils approach, but modifying the commands it runs slightly.
In dos you can get the free and total bytes with the fsutil command:
on my box this gives the following results:
On Unix, the command is still "df -k", you’re just interested in the "1024-blocks" column to the left of "Free" (example from Wikipedia below). You obviously need to multiply the result by 1024.
Assuming you copy FileSystemUtils to implement "totalSpaceKB()" to delegate to an equivalent OS-specific method. The implementation for Windows would be something like this (note the use of "Find" to trim the output from fsutil to just get the total size):
The implementation for Unix would be the same as freeSpaceUnix(), but remove the two calls to tok.nextToken() at the end of the method
The implementations for other platforms would be similar.
Hope this helps and apologies agian for misreading the problem.
Original answer (gets free bytes, not total).
Prior to Java 6 there isn’t an elegant way to do this, (see the bug). Rather than rolling your own, I’d recommend using a library to do the platform-specific processing for you.
Apache commons-io has a FileSystemUtils type that provides a static method freeSpaceKb(). It works on Windows and and some Unix implementations (see quote from Javadoc below)
From the Javadoc: