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

来源:互联网 发布:在线生成数据统计图表 编辑:程序博客网 时间:2024/04/30 11:22

以下两个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());         }     } }


原创粉丝点击