Generally speaking, to use Java to get hard disk space, there are 3 ways:
1. Call the system command, and then analyze the resulting results, this method has a strong system-dependent, Linux and win under the separate write program
Here is a win under the example, after the successful compilation, run Java DiskSpace yourdir (such as C:\)
import Java.io.BufferedReader;
import Java.io.InputStreamReader;
/**
* Determine free disk spaces for a given directory by
* Parsing the output of the dir command.
* This class are inspired by the code at
* Works only under Windows under certain circumstances.
* Yes, it´s that shaky.
* Requires Java 1.4 or higher.
* @[email PROTECTED]
*marco Schmidt
*/
public class DiskSpace
{
Private diskspace ()
{
//Prevent instantiation of this class
}
/**
* Return available free disk spaces for directory A.
* @[email PROTECTED]
dirname Name of the directory
* @[email PROTECTED]
free disk spaces in bytes or-1 if unknown
*/
public static Long Getfreediskspace (String dirname)
{
Try
{
//Guess Correct´dir´command by looking at the
//Operating system name
String os = System.getproperty ("Os.name");
String command;
if (os.equals ("Windows NT") | |
os.equals ("Windows 2000"))
{
command = "cmd.exe/c dir" + dirname;
}
Else
{
command = "command.com/c dir" + dirname;
}
//Run the dir command on the argument directory name
Runtime Runtime = Runtime.getruntime ();
process process = NULL;
Process = runtime.exec (command);
if (process = null)
{
return-1;
}
//Read the output of the dir command
//Only the "last" is of interest
BufferedReader in = new BufferedReader (
New InputStreamReader (Process.getinputstream ()));
String Line;
String freeSpace = null;
while (line = In.readline ())!= null)
{
freeSpace = line;
}
if (freeSpace = null)
{
return-1;
}
Process.destroy ();
/Remove Dots & commas & leading and trailing whitespace
freeSpace = Freespace.trim ();
freeSpace = Freespace.replaceall ("\.", "");
freeSpace = Freespace.replaceall (",", "");
string[] items = Freespace.split ("");
//The the valid numeric value in items after (!) index 0
//is probably the free disk space
int index = 1;
while (Index < items.length)
{
Try
{
Long bytes = Long.parselong (items[index++));
return bytes;
}
catch (NumberFormatException nfe)
{
}
}
return-1;
}
catch (Exception Exception)
{
return-1;
}
}
/**
* Command Line program to print the free diskspace to stdout
* For all potential root directories a:\ to z:\
* (when no parameters are given)
* or for those directories (drives) specified as parameters.
* @[email PROTECTED]
Args Program Parameters
*/
public static void Main (string[] args)
{
if (args.length = 0)
{
for (char c =´a´ <=´Z´; C + +)
{
String dirname = c + ": \ \";
System.out.println (dirname + "" +
Getfreediskspace (dirname));
}
}
Else
{
for (int i = 0; i < args.length; i++)
{
System.out.println (Args[i] + "" +
Getfreediskspace (Args[i]);
}
}
}
}