views:

803

answers:

3

I want to get the size of a drive (or UNC path pointing to a partition would be nice, but not required), as well as free space for said drive (or UNC path). This doesn't need to work cross platform; only in Windows.

I know it's easy to do in Java 6, but that's not an option; I'm stuck with Java 5.

I can get the free space available by doing:

cmd.exe /c Z:\ /-c

or

cmd.exe /c \\server\share /-c

and just parsing out the resulting bytes free. However I can't seem to find a way to get the total drive size.

Any suggestions?

+3  A: 

One way to do it would be to use fsutil on the command line. It returns something like this:

D:\>fsutil fsinfo ntfsinfo c:
NTFS Volume Serial Number :       0xd49cf9cf9cf9ac5c
Version :                         3.1
Number Sectors :                  0x0000000004a813ff
Total Clusters :                  0x000000000095027f
Free Clusters  :                  0x00000000002392f5
Total Reserved :                  0x0000000000000490
Bytes Per Sector  :               512
Bytes Per Cluster :               4096
Bytes Per FileRecord Segment    : 1024
Clusters Per FileRecord Segment : 0
Mft Valid Data Length :           0x000000000e70c000
Mft Start Lcn  :                  0x00000000000c0000
Mft2 Start Lcn :                  0x0000000000000010
Mft Zone Start :                  0x0000000000624ea0
Mft Zone End   :                  0x0000000000643da0

Multipy your number of sectors times the bytes per sector to get your size.

DMKing
this won't work for network drives, but i think this is as good as it's going to get
Alex Beardsley
+1  A: 

You could do this pretty easily using a JNI call if you are comfortable with that...

If you want a pre-packaged library that you can use with JDK1.5, take a look at the Apache FileSystemUtils

This just wraps the system call that you describe, but at least it's a standard library that you can use until you are able to use 1.6.

Kevin Day
Actually, FileSystemUtils goes via the command line, using the dir command. And it only supports free size, not total size.
Wouter Lievens
A: 

You could use the SIGAR library, which gives you native access on many platforms.

zehrer