Reputation: 46616
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.
Upvotes: 1
Views: 1435
Reputation: 15789
Apache Commons has FileSystemUtils.freeSpaceKb() that will work cross platfrom etc etc
Upvotes: 0
Reputation: 6409
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....
Upvotes: 1
Reputation: 66333
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 };
Upvotes: 3