If it's that simple - how do you get the total disk space? And who wants to iterate over all 32,000 files on a filesystem to obtain an inaccurate assessment of used space? Not to mention that any space used by metadata won't generally be reported by File.length() so disk free space won't be accurate, anyway.
I would look at JConfig.
http://www.tolstoy.com/samizdat/jconfig.html
I used native methods, written in C/C++ (jpath is the path of a directory where you need the disk space, such as "c:\"):
// Returns amount of free disk space
// Returns -1 on error
JNIEXPORT jlong JNICALL Java_com_diskFree
(JNIEnv *env, jclass cls, jstring jPath)
{
long freeMb = -1;
char*path;
#ifdef _WINDOWS
ULARGE_INTEGER freeAvail;
ULARGE_INTEGER totalBytes;
ULARGE_INTEGER freeBytes;
#else
struct statvfs buf;
#endif
path = (char *)((*env)->GetStringUTFChars(env, jPath, NULL));
#ifdef _WINDOWS
if (GetDiskFreeSpaceEx(path,
&freeAvail, &totalBytes, &freeBytes) > 0)
{
if ((freeAvail.QuadPart/1000000) >= LONG_MAX)
freeMb = LONG_MAX;
else if ((freeAvail.QuadPart/1000000) > 1)
freeMb = (freeAvail.QuadPart/(1024 * 1024));
if (freeMb < 0)
{
if ((freeBytes.QuadPart/1000000) >= LONG_MAX)
freeMb = LONG_MAX;
else if ((freeBytes.QuadPart/1000000) > 1)
freeMb = (freeBytes.QuadPart/(1024 * 1024));
}
}
#else
if (statvfs(path, &buf) == 0)
freeMb = buf.f_bavail * buf.f_frsize / (1024 * 1024);
#endif
(*env)->ReleaseStringUTFChars(env, jPath, path);
return freeMb;
}
I work on a Windows Platform and did a method like this:
public static String getFreeDiskSpace() throws IOException {
Runtime rt = Runtime.getRuntime();
Process p = rt.exec("a.bat");
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String value = "";
String s = null;
while ((s = br.readLine()) != null)
value = s;
return value.trim();
}
The "a.bat" file looks like this:
dir
That means that the method runs the "dir"-command, retrieves the output from the dir and returns the last row which includes the number of free bytes. Of course, this line can be parsed if necessary.
Sample return from dir:
C:\OMlink3.x\nordiska\OMLINK3.1\src>dir
Volume in drive C has no label.
Volume Serial Number is CCCE-4A7B
Directory of C:\src
02-10-30 16:26 <DIR> .
02-10-30 16:26 <DIR> ..
02-10-30 16:13 3 a.bat
02-10-22 15:473 545 compile.bat
02-10-30 16:262 149 DiskTest.class
02-10-30 16:261 342 DiskTest.java
02-08-19 09:20 <DIR> om
02-10-22 15:551 136 settings.bat
02-10-22 15:47 64 vssver.scc
02-10-30 16:26 0 x.txt
10 File(s) 8 239 bytes
244 345 856 bytes free
In this case, my method returns "244 345 856 bytes free".
Hope this helps someone.
/Hampus