Click to See Complete Forum and Search --> : Available hard disk space in Java


WaRmAsTeR
05-07-2003, 11:48 AM
Hi,

I have a program in Java that I built in order to move files from one disk to another (kind of backup) depending on the date they were created.
Now I want to check the available disk space in a thread, and report an error (send an e-mail) if the disk space gets below a certain threshold.
How would I determine the disk space remaining?
Thanks!

cjohnson
05-07-2003, 12:34 PM
I don't know of any portable/Java-ish way to do that... only thing I could think of is making Java execute 'df -h' (if you're on a UNIX) and parse that correctly... i assume there's a similar command on windows systems.

EverlastingGod
05-07-2003, 12:45 PM
Originally posted by cjohnson
I don't know of any portable/Java-ish way to do that... only thing I could think of is making Java execute 'df -h' (if you're on a UNIX) and parse that correctly... i assume there's a similar command on windows systems.

Yeah, I don't think there's a pure-Java way to do it.

WaRmAsTeR
05-07-2003, 01:07 PM
My program will only be running on Windows...
How would I do it then?

EverlastingGod
05-07-2003, 01:36 PM
Do what cjohnson said, capture the output of a command (like dir) and parse it

or

Find the Windows function that checks diskspace and call it using JNI.

rock
05-08-2003, 08:38 AM
First, there's an enhancement request for this feature here. (http://developer.java.sun.com/developer/bugParade/bugs/4057701.html) .

Next, the current way of doing this is allocating progressively larger amounts of space until an exception is thrown. Consider the following method (not written by me). Note that the space is allocated, but not actually written.

public long getDiskSpace(File path) throws IOException {
File file = File.createTempFile("dummy","none", path);
RandomAccessFile raf = new RandomAccessFile(file, "rw");

long size = 0;
long step = Long.MAX_VALUE - (Long.MAX_VALUE/2);

while (step > 0) {
try {
raf.setLength(size + step);
size += step;
}
catch (IOException ioe) {}
step /= 2;
}
raf.close();
file.delete();
return size;
}

EverlastingGod
05-08-2003, 11:33 AM
I don't know. Wouldn't allocating the space be bad even if you're not writing to it?

OS-Wiz
05-08-2003, 01:02 PM
Originally posted by EverlastingGod
I don't know. Wouldn't allocating the space be bad even if you're not writing to it? Its possible that for a very short period of time (before the file is deleted) another process could fail an allocation attempt. I'd go with a Windows command to determine space available.

EverlastingGod
05-08-2003, 04:55 PM
Hehe, I was being sarcastic and rhetorical.

:p

WaRmAsTeR
05-09-2003, 09:44 AM
Thanks a lot for the code!

It works great except we are not sure if we are going to implement this functionnality because this is going to run on a server and we want to be sure that the disk will never be full...