查看磁盘剩余空间:Java代码改进

  【虎.无名】最近封装JMX的MBean,有一个监控磁盘空间的需求。在网上找遍了,列出了3种方法,第1种只能windows系统,第2种就不用说了,需要一个扩展库。至于用JNI则就没必要了。最新的jdk6.0有相应的方法,其它版本还没有,研究了一下方法一和方法二,主要原理就是:通过java中的Process类来调用外部命令,如dir、ls、df -k、du等,然后捕获其标准输出,从而获取所需数据。具体代码如下。。。

方法一:执行外部命令dir/df,然后捕获输出,分析输出获取所需数据。
原始代码地址: http://www.jr163.org/cup2/36/36934.htm
【虎.无名】原始代码存在缺陷,未处理win xp,而且不支持unix等操作系统;经过修改后的代码见附录。

方法二:使用Jconfig,可以跨平台
  从http://www.tolstoy.com/samizdat/jconfig.html上下载jconfig。
  下载的包的sample里有很简单的例子,如果是要得到磁盘空间的话:
  用FileRegistry.getVolumes()得到DiskVolume。
  然后call getFreeSpace()和getMaxCapacity()。
  就是这么简单。

方法三:使用jni技术 【虎.无名】针对需求而言太复杂,也无法移植,不建议使用。
  这个是解决所有和os相关的操作的万能利器了。
  例子我也懒得写了。
  写一个dll然后call之即可。

http://tolstoy.com/samizdat/jconfig.html

What is it?
JConfig is a cross-platform library that supplements the core Java API and solves many programming tasks.

It lets you work with files, web browsers, processes, file types, and other system-level items in a much more advanced manner than that provided by the standard Java class libraries. For instance, you can use it to launch web browsers or other external applications instead of using Runtime.exec or solutions that only work on one platform.

JConfig is similar to some of the Microsoft extensions to Java, except: it's completely cross-platform! JConfig runs on Windows, Mac, Unix, and other platforms to come.

The download even includes the complete source code!

See how JConfig compares with the standard Java API.

What can I do with it?
Here's a partial list, by category:

Files: Enumerate the user's disk drives, and obtain extended information on files, directories, volumes, and filesystems: their icons, creation dates, version information, mount points, and much more...
Web Browsers: Launch a file or URL in the user's Web browser...
Video Monitors: Enumerate and get information on the user's video monitors: bit depth, bounds, etc...
External Processes: Create external processes, send basic commands to external processes, obtain the PSN or HWND of a process you created, and enumerate the currently running processes...
File Types: Find applications associated with a given file type, find applications by name, and convert between Windows file extensions and Mac creator/file type codes...
--------

【虎.无名】修改后的DiskSpace代码及测试。

Java代码 复制代码
  1. public class DiskSpace {   
  2.  public static final String CRLF = System.getProperty("line.separator");   
  3.  public static final int OS_Unknown  = 0;   
  4.  public static final int OS_WinNT  = 1;   
  5.  public static final int OS_Win9x  = 2;   
  6.  public static final int OS_Linux  = 3;   
  7.  public static final int OS_Unix  = 4;   
  8.     
  9.  private static Log   _log = LogFactory.getLog(DiskSpace.class);   
  10.  private static String  _os = System.getProperty("os.name");   
  11.  protected static String os_exec(String[] cmds) {   
  12.   int   ret = 0;   
  13.   Process  porc = null;   
  14.   InputStream perr = null, pin = null;    
  15.   StringBuffer sb = new StringBuffer();   
  16.   String  line = null;   
  17.   BufferedReader br = null;   
  18.   try {   
  19.   // for(int i=0; i   porc = Runtime.getRuntime().exec(cmds);//执行编译操作   
  20.   // porc = Runtime.getRuntime().exec(cmds, null, null);   
  21.    perr = porc.getErrorStream();   
  22.    pin  = porc.getInputStream();   
  23.    //获取屏幕输出显示   
  24.    //while((c=pin.read())!=-1) sb.append((char) c);   
  25.    br = new BufferedReader(new InputStreamReader(pin));   
  26.    while((line=br.readLine())!=null) {   
  27.    // System.out.println("exec()O: "+line);   
  28.     sb.append(line).append(CRLF);   
  29.    }   
  30.    //获取错误输出显示   
  31.    br = new BufferedReader(new InputStreamReader(perr));   
  32.    while((line=br.readLine())!=null) {   
  33.     System.err.println("exec()E: "+line);   
  34.    }   
  35.    porc.waitFor();   //等待编译完成      
  36.    ret = porc.exitValue(); //检查javac错误代码   
  37.    if (ret!=0) {   
  38.     _log.warn("porc.exitValue() = "+ret);   
  39.    }      
  40.   }catch(Exception e) {   
  41.    _log.warn("exec() "+e, e);   
  42.   }finally {   
  43.    porc.destroy();   
  44.   }   
  45.   return sb.toString();   
  46.  }   
  47.     
  48.  protected static int os_type() {   
  49.         //_log.debug("os.name = "+os); //Windows XP   
  50.         String os = _os.toUpperCase();   
  51.         if (os.startsWith("WINDOWS")) {   
  52.          if (os.endsWith("NT") || os.endsWith("2000") || os.endsWith("XP"))   
  53.           return OS_WinNT;   
  54.          else return OS_Win9x;   
  55.         }else if (os.indexOf("LINUX")>0return OS_Linux;   
  56.         else if (os.indexOf("UX")>0)   return OS_Unix;   
  57.         else           return OS_Unknown;   
  58.   }   
  59.  protected static long os_freesize(String dirName) {   
  60.   String[] cmds = null;   
  61.   long freeSize = -1;   
  62.   int osType = os_type();   
  63.   switch(osType) {   
  64.   case OS_WinNT:    
  65.    cmds = new String[]{"cmd.exe""/c""dir", dirName};   
  66.    freeSize = os_freesize_win(os_exec(cmds));   
  67.    break;   
  68.   case OS_Win9x:    
  69.    cmds = new String[]{"command.exe""/c""dir", dirName};   
  70.    freeSize = os_freesize_win(os_exec(cmds));   
  71.    break;   
  72.   case OS_Linux:   
  73.   case OS_Unix:   
  74.    cmds = new String[]{"df", dirName};   
  75.    freeSize = os_freesize_unix(os_exec(cmds));   
  76.    break;   
  77.   default:   
  78.   }   
  79.   return freeSize;   
  80.  }   
  81.  protected static String[] os_split(String s) {   
  82. //  _log.debug("os_split() "+s);   
  83.   String[] ss = s.split(" "); //空格分隔;   
  84.   List ssl = new ArrayList(16);   
  85.   for(int i=0; i   if (ss[i]==null)  continue;   
  86.    ss[i] = ss[i].trim();   
  87.    if (ss[i].length()==0continue;   
  88.    ssl.add(ss[i]);   
  89. //   _log.debug("os_split() "+ss[i]);   
  90.   }   
  91.   String[] ss2 = new String[ssl.size()];   
  92.   ssl.toArray(ss2);   
  93.   return ss2;   
  94.  }   
  95.  private static long os_freesize_unix(String s) {   
  96.   String lastLine = os_lastline(s); //获取最后一航;   
  97.   if (lastLine == null) {   
  98.          _log.warn("(lastLine == null)"); return -1;   
  99.         }else lastLine = lastLine.trim();   
  100.   //格式:/dev/sda1    101086     12485     83382  14% /boot   
  101.   //lastLine = lastLine.replace('/t', ' ');   
  102.   String[] items = os_split(lastLine);   
  103.   _log.debug("os_freesize_unix() 目录:/t"+items[0]);   
  104.   _log.debug("os_freesize_unix() 总共:/t"+items[1]);   
  105.   _log.debug("os_freesize_unix() 已用:/t"+items[2]);   
  106.   _log.debug("os_freesize_unix() 可用:/t"+items[3]);   
  107.   _log.debug("os_freesize_unix() 可用%:/t"+items[4]);   
  108.   _log.debug("os_freesize_unix() 挂接:/t"+items[5]);   
  109.   if(items[3]==null) {   
  110.    _log.warn("(ss[3]==null)");   return -1;   
  111.   }   
  112.   return Long.parseLong(items[3])*1024//按字节算   
  113.  }   
  114.  private static long os_freesize_win(String s) {   
  115.   String lastLine = os_lastline(s); //获取最后一航;   
  116.   if (lastLine == null) {   
  117.          _log.warn("(lastLine == null)");   
  118.             return -1;   
  119.         }else lastLine = lastLine.trim().replaceAll(",""");   
  120.   //分析     
  121.   String items[] = os_split(lastLine); //15 个目录  1,649,696,768 可用字节   
  122.   if (items.length<4) { _log.warn("DIR result error: "+lastLine); return -1;}   
  123.   if (items[2]==null) { _log.warn("DIR result error: "+lastLine); return -1;}   
  124.         long bytes = Long.parseLong(items[2]); //1,649,696,768    
  125.         return bytes;   
  126.  }   
  127.  protected static String os_lastline(String s) {   
  128.   //获取多行输出的最后一行;   
  129.   BufferedReader br = new BufferedReader(new StringReader(s));   
  130.   String line = null, lastLine=null;   
  131.   try {   
  132.    while((line=br.readLine())!=null) lastLine = line;   
  133.   }catch(Exception e) {   
  134.    _log.warn("parseFreeSpace4Win() "+e);   
  135.   }   
  136.   //_log.debug("os_lastline() = "+lastLine);   
  137.   return lastLine;     
  138.  }   
  139. // private static String os_exec_df_mock() { //模拟df返回数据   
  140. //  StringBuffer sb = new StringBuffer();   
  141. //  sb.append("Filesystem     1K-块        已用     可用 已用% 挂载点");   
  142. //  sb.append(CRLF);   
  143. //  sb.append("/dev/sda1    101086     12485     83382  14% /boot");   
  144. //  sb.append(CRLF);   
  145. //  return sb.toString();   
  146. // }   
  147.     public static long getFreeDiskSpace(String dirName) {   
  148.         //return os_freesize_unix(os_exec_df_mock()); //测试Linux   
  149.   return os_freesize(dirName);//自动识别操作系统,自动处理   
  150.     }   
  151.     public static void main(String[] args) throws IOException {   
  152.      UtilLog.configureClassPath("resources/log4j.properties"false);   
  153.      args = new String[3]; int x=0;   
  154.      args[x++] = "C:";     args[x++] = "D:"; args[x++] = "E:";   
  155.         if (args.length == 0){   
  156.             for (char c = 'A'; c <= 'Z'; c++) {   
  157.                 String dirName = c + "://";  //C:/ C:   
  158.                 _log.info(dirName + " " +   
  159.                 getFreeDiskSpace(dirName));   
  160.             }   
  161.         }else{   
  162.             for (int i = 0; i < args.length; i++) {   
  163.              _log.info(args[i] + " 剩余空间(B):" + getFreeDiskSpace(args[i]));   
  164.             }   
  165.         }   
  166.     }   
  167. }  
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值