日期:2014-05-17  浏览次数:20911 次

win2000和XP下得到硬盘剩余空间(用java调用windows命令)

package tigers;

import java.io.*;


public class Tiger19 {

?public static void main(String[] args) {
? try {
?? for (char c = 'A'; c <= 'Z'; c++ ) {
??? String dirName = c + ":\\";
??? long freeSpace = getFreeDiskSpace(dirName);
??? if (freeSpace != -1) {
???? long number = Math.round(freeSpace / (1024.00 * 1024.00));
???? System.out.println("<+>>>>" + dirName + " 剩余空间为: " + number + "MB");
??? }
?? }
? } catch (Exception e) {
?? e.printStackTrace();
? }
?}
?private static long getFreeDiskSpace(String dirName) throws Exception {
? String osName = System.getProperty("os.name");
? if (!(osName.equalsIgnoreCase("windows XP") || osName.equalsIgnoreCase("windows 2000"))) return -1;
? String command = "cmd exe /c dir " + dirName; //操作系统命令
? Process process = Runtime.getRuntime().exec(command); //执行操作系统命令。
? if (process == null) return -1;
? BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
? String line = "";
? String lastLine = "";
? while ((line = br.readLine()) != null) { //依次一行行读取,但while循环的目的只是得到最后一行字符。
?? System.out.println(line);
?? lastLine = line;
? }
? lastLine = lastLine.replaceAll(",", ""); //去掉如2,146,623,488中间的逗号。
? String[] items = lastLine.split(" ");
? long freeSpace = -1;
? for (int i = (items.length - 1); i > 0; i--) { //从最后一个字符串开始遍历。
?? try {
??? freeSpace = Long.parseLong(items[i]);
??? break; //如果找到目的数据就跳出循环。
?? } catch (NumberFormatException nfe) {
??? continue; //跳过不是数字的字符。
?? }
? }
? return freeSpace;
?}
}

?


转载请标明出处:http://blog.csdn.net/ggjjzhzz/archive/2005/03/16/321284.aspx