java 代码中如何取得硬盘的使用率(可以用API)

解决方案 »

  1.   

    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)
      {
      freeSpace = line;
      }
      if (freeSpace == null)
      {
      return -1;
      }
      process.destroy();
      // remove dots & commas & leading and trailing whitespace
      freeSpace = freeSpace.trim();
      freeSpace = freeSpace.replaceAll("\\.", "");
      freeSpace = freeSpace.replaceAll(",", "");
      String[] items = freeSpace.split(" ");
      // the first valid numeric value in items after(!) index 0
      // is probably the free disk space
      int index = 1;
      while (index < items.length)
      {
      try
      {
      long bytes = Long.parseLong(items[index++]);
      return bytes;
      }
      catch (NumberFormatException nfe)
      {
      }
      }
      return -1;
      }
      catch (Exception exception)
      {
      return -1;
      }
      }
      
      /**
      * Command line program to print the free diskspace to stdout
      * for all 26 potential root directories A:\ to Z:* (when no parameters are given to this program)
      * or for those directories (drives) specified as parameters.
      * @[EMAIL PROTECTED]
      args program parameters
      */
      public static void main(String[] args)
      {
      if (args.length == 0)
      {
      for (char c = 'A'; c <= 'Z'; c++)
      {
      String dirName = c + ":\\";
      System.out.println(dirName + " " +
      getFreeDiskSpace(dirName));
      }
      }
      else
      {
      for (int i = 0; i < args.length; i++)
      {
      System.out.println(args[i] + " " +
      getFreeDiskSpace(args[i]));
      }
      }
      }
      }
      
      方法二:使用Jconfig,可以跨平台
      从http://www.tolstoy.com/samizdat/jconfig.html上下载jconfig.
      下载的包的sample里有很简单的例子,如果是要得到磁盘空间的话:
      用FileRegistry.getVolumes()得到DiskVolume
      然后call getFreeSpace()和getMaxCapacity()
      就是这么简单..:)
      

  2.   

    这个方法我在网上找到过的,没有直接的WINDOWS API可一掉用吗?
      

  3.   

    你先试一下吧,具体的windows api还真的是不清楚啊,呵呵
      

  4.   

    这个方法我在网上找到过的,没有直接的WINDOWS API可一掉用吗?
    调用WINDOWS命令和直接调用WINDOWS API又没社么区别~~
      

  5.   

    lixiaoxue85(蛮野蛮) ( )  什么时候变成一个星星的?
      

  6.   

    jre6.0方法:
    long totalSpace = 0L;
    long freeSpace = 0L;
    for (int i=0;i<File.listRoots().length;i++)
    {
      File file = new File(File.listRoots()[i]);
        totalSpace += file.getTotalSpace();
        freeSpace += file.getFreeSpace();
    }
    System.out.println((totalSpace-freeSpace)/totalSpace);
      

  7.   

    jre6.0方法:
    long totalSpace = 0L;
    long freeSpace = 0L;
    for (int i=0;i<File.listRoots().length;i++)
    {
      File file = File.listRoots()[i];
        totalSpace += file.getTotalSpace();
        freeSpace += file.getFreeSpace();
    }
    System.out.println((totalSpace-freeSpace)/totalSpace);
      

  8.   

    本人用的是JDK1.4的,解决方法如下:
        public static String getDiskUseRate() throws Exception{     String freeSize = null;
         String totalSize = null;
         String line;
         String[] cmdarray = {Consts.DISKPATH + "disk.bat"};
            Process process = Runtime.getRuntime().exec(cmdarray);
            InputStream is = process.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            
            while ((line = br.readLine()) != null) {
                if(line.indexOf("FreeSpace")!=-1){
                 freeSize = line.substring(line.indexOf(":")+1).trim();
                }else if(line.indexOf("TotalSize")!=-1){
                 totalSize = line.substring(line.indexOf(":")+1).trim();
                }
            }
            
            double num = (Long.parseLong(totalSize) - Long.parseLong(freeSize) )/ (double)Long.parseLong(totalSize);        DecimalFormat decimalFormat = new DecimalFormat("##.#%");
            return (decimalFormat.format(num));    }
    disk.bat里内容:
    cscript c:\\disk.vbsdisk.vbs里内容:
    Set objFSO = WScript.CreateObject("Scripting.FileSystemObject")
    Set objDrive = objFSO.GetDrive("c")
    WScript.Echo "FreeSpace      : " & objDrive.FreeSpace
    WScript.Echo "TotalSize      : " & objDrive.TotalSize这样就解决了,谢谢各位了....结贴了