java获取主机磁盘信息:包括盘符,空闲,已使用等信息。
getFreeSpace()、getUsableSpace、getTotalSpace等方法都是JDK1.6 中的。
现在用JDK1.5。
本地开发测试环境Windows,服务器 Linux。

解决方案 »

  1.   

    windows下原理,使用dir命令,下面是取剩余空间的源码, 其它同理 public static long freeSpaceWindows(String path) throws IOException{
    if(path.length() > 2 && path.charAt(1) == ':'){
    path=path.substring(0,2); // seems to make it work
    }
    String[] cmdAttrbs=new String[]{"cmd.exe","/C","dir /-c " + path}; BufferedReader in=null;
    String line=null;
    ArrayList<String> lines=new ArrayList<String>();
    try{
    Process proc=Runtime.getRuntime().exec(cmdAttrbs);
    in=new BufferedReader(new InputStreamReader(proc.getInputStream()));
    line=in.readLine();
    while(line != null){
    line=line.toLowerCase().trim();
    lines.add(line);
    line=in.readLine();
    }
    }
    finally{
    in.close();
    } if(lines.size() == 0){
    throw new IOException("Command line 'dir /c' did not return any info " + "for command '" + cmdAttrbs[2] + "'");
    } long bytes=-1;
    int i=lines.size() - 1;
    int bytesStart=0;
    int bytesEnd=0;
    outerLoop:while(i > 0){
    line=(String)lines.get(i);
    if(line.length() > 0){
    int j=line.length() - 1;
    innerLoop1:while(j >= 0){
    char c=line.charAt(j);
    if(Character.isDigit(c)){
    bytesEnd=j + 1;
    break innerLoop1;
    }
    j--;
    }
    innerLoop2:while(j >= 0){
    char c=line.charAt(j);
    if(!Character.isDigit(c) && c != ',' && c != '.'){
    bytesStart=j + 1;
    break innerLoop2;
    }
    j--;
    }
    break outerLoop;
    }
    } StringBuffer buf=new StringBuffer(line.substring(bytesStart,bytesEnd));
    for(int k=0;k < buf.length();k++){
    if(buf.charAt(k) == ',' || buf.charAt(k) == '.'){
    buf.deleteCharAt(k--);
    }
    }
    bytes=Long.parseLong(buf.toString());
    return bytes;
    }
      

  2.   

    freeSpaceWindows(String path)  path 是指什么参数?什么含义
      

  3.   

    使用SIGAR - System Information Gatherer And Reporter吧The Sigar API provides a portable interface for gathering system information such as:System memory, swap, cpu, load average, uptime, logins
    Per-process memory, cpu, credential info, state, arguments, environment, open files
    File system detection and metrics
    Network interface detection, configuration info and metrics
    TCP and UDP connection tables
    Network route tablehttp://support.hyperic.com/display/SIGAR/Home#Home-overview
      

  4.   


    比如取C盘的
    freeSpaceWindows("c:")