java查看硬盘指定目录剩余空间 for win

来源:互联网 发布:知乎 隐藏优惠券 编辑:程序博客网 时间:2024/05/21 15:03


import java.io.*;

public class TT {


 public float freeSpace() throws IOException{
  // TODO Auto-generated method stub

     String  command = "cmd.exe /c dir e:";
        Runtime runtime = Runtime.getRuntime();
        Process process = null;
        process = runtime.exec(command);
       
        BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line;
        String freeSpace = null;
    
     while ((line = in.readLine()) != null)
    {
      freeSpace = line;
     }
     process.destroy();

     freeSpace = freeSpace.trim();
     freeSpace = freeSpace.replaceAll("//.", "");
     freeSpace = freeSpace.replaceAll(",", "");
        String[] items = freeSpace.split(" ");
       
      int index = 1;
      float f = 1024*1024*1024;
      while (index < items.length)
      {
       //System.out.println("dsfa");
        try
        {
           long bytes = Long.parseLong(items[index++]);
           System.out.println(bytes/f);
           return bytes/f;
         }catch (NumberFormatException nfe)
                {  }
       }
  return -1;
    }
 public static void main(String[] args) throws IOException {
  TT t = new TT();
  System.out.println(t.freeSpace());
 }
}
 

原创粉丝点击