1

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 Answers 3

3

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 };
1
  • Thanks mate. I got the solution from Apache Commons IO, but didn't know the explanation behind.
    – glmxndr
    Aug 7, 2009 at 12:56
1

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....

2
  • 1
    Or use JNA to avoid the complexities of JNI compilation and setup. Aug 7, 2009 at 13:20
  • -0.5 Violas are not supported by Java :-)
    – Stephen C
    Aug 7, 2009 at 13:44
0

Apache Commons has FileSystemUtils.freeSpaceKb() that will work cross platfrom etc etc

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.