第一章 Java編程獲取硬盤空間(1 / 2)

第一章 Java編程獲取硬盤空間

因為論壇有人問到這個問題,所以就寫了這篇文章。希望對大家有所幫助。

一般來講,要用java得到硬盤空間,有3種方法:

1. 調用system的command,然後分析得到的結果,這種方法有很強的係統依賴性,linux下和win下要分別寫程序。

下麵是一個win下的例子,編譯成功之後,運行java Diskspace yourdir(比如c:\)

import java.io.BufferedReader;

import java.io.InputStreamReader;

/**

* Determine free disk space for a given directory by

* parsing the output of the dir command.

* This class is 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 space for a directory.

* @[EMAIL PROTECTED]

dirName name of the directory

* @[EMAIL PROTECTED]

free disk space 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 line is of interest

BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));

String line;

String freeSpace = null;

while ((line = in.readLine()) != null)