java查看磁盘空间的两个版本

以下两个java类在windows7上测试通过。

1、给出jdk1.5版本的。

package test;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class SpaceChecker {
	public static void main(String[] args) {
		String os,command,line,spaceSpliter="";
		Process process=null;
		try {
	        os = System.getProperty("os.name");//获取当前操作系统,不同的系统的命令可能不同,可以根据该值采取不同的策略。
			command = " wmic LogicalDisk where \"Caption='D:'\" get FreeSpace,Size";//这里以D盘为例
			Runtime runtime = Runtime.getRuntime();
			process = runtime.exec(command);
			process.waitFor();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					process.getInputStream()));
			int counter = 0;
			while ((line = in.readLine()) != null) {
				counter++;
				if (counter == 3)//第三行是需要的数据
					break;
			}
			process.destroy();
			line = line.trim();
			for(int i=0;i<line.length();i++){
				if (line.substring(i, i+1).equals(" ")) spaceSpliter+=" ";
			}
			String[] items = line.split(spaceSpliter);//中间是n个空格
			long freeBytes = Long.parseLong(items[0]);
			long totalBytes = Long.parseLong(items[1]);
			System.out.println("freeSpace:"+freeBytes/1024/1024/1024+"G");
			System.out.println("size:"+totalBytes/1024/1024/1024+"G");
		} catch (Exception exception) {
			exception.printStackTrace();
		}
	}
}

 

2、给出1.6版本的。

import java.io.File;
 
 public class SpaceChecker {
     public static void main(String[] args) {
         File[] roots = File.listRoots();
         for (File _file : roots) {
             System.out.println(_file.getPath());
             System.out.println("Free space = " + _file.getFreeSpace());
             System.out.println("Usable space = " + _file.getUsableSpace());
             System.out.println("Total space = " + _file.getTotalSpace());
         }
     }
 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值