views:

544

answers:

2

I want to determine the available disk space on windows. I don't care that my code is not portable. I use this :

String[] command = {"dir",drive};
Process process = Runtime.getRuntime().exec(command);
InputStream result = process.getInputStream();

aiming to parse the result from a "dir C:" type of call, but the String I get from the command line call is as if I called dir with a /W option (not giving any information about file sizes or disk usage / free space). (Although when I launch dir C: directly from the command line, I get the expected result, so there is no dir particular setup on my system.) Trying to pass a token /-W or on any other option seems not to work : I just get the name of the folders/files contained in the drive, but no other information whatsoever.

Someone knows a fix / workaround ?

NOTE:

I can't go along the fsutil route, because fsutil does not work on network drives.

+3  A: 

It sounds like your exec() is finding a program called "dir" somewhere in your path because with your String[] command as it is I would otherwise expect you to get an IOException (The system cannot find the file specified). The standard dir command is built into the cmd.exe Command Prompt and is not a standalone program you can execute in its own right.

To run the dir command built into cmd.exe you need to use the /c switch on cmd.exe which executes the specified command and then exits. So if you want to execute:

cmd /c dir

your arguments to pass to exec would be:

String[] command = { "cmd", "/c", "dir", drive };
mikej
Thanks mate. I got the solution from Apache Commons IO, but didn't know the explanation behind.
subtenante
+1  A: 

If you don't care about portability, use the GetDiskFreeSpaceEx method from Win32 API. Wrap it using JNI, and viola!

Your Java code should look like:

public native long getFreeSpace(String driveName);

and the rest can be done through the example here. I think that while JNI has its performance problems, it is less likely to cause the amount of pain you'll endure by using the Process class....

Aviad Ben Dov
Or use JNA to avoid the complexities of JNI compilation and setup.
Robin Smidsrød
Great, didn't know of JNA!
Aviad Ben Dov
-0.5 Violas are not supported by Java :-)
Stephen C
Damn! Voila! VOILA!
Aviad Ben Dov