发布时间:2018-03-25作者:laosun阅读(13078)
java 获取Linux 的磁盘使用空间。这样的话,可以在系统后台随时监控linux的磁盘使用情况。其实原理很简单,就是使用java执行Linux执行,然后解析显示结果
// _ooOoo_ // o8888888o // 88" . "88 // (| -_- |) // O\ = /O // ____/`---'\____ // . ' \\| |// `. // / \\||| : |||// \ // / _||||| -:- |||||- \ // | | \\\ - /// | | // | \_| ''\---/'' | | // \ .-\__ `-` ___/-. / // ___`. .' /--.--\ `. . __ // ."" '< `.___\_<|>_/___.' >'"". // | | : `- \`.;`\ _ /`;.`/ - ` : | | // \ \ `-. \_ __\ /__ _/ .-` / / // ======`-.____`-.___\_____/___.-`____.-'====== // `=---=' // // ............................................. // 佛祖保佑 永无BUG // 佛曰: // 写字楼里写字间,写字间里程序员; // 程序人员写程序,又拿程序换酒钱。 // 酒醒只在网上坐,酒醉还来网下眠; // 酒醉酒醒日复日,网上网下年复年。 // 但愿老死电脑间,不愿鞠躬老板前; // 奔驰宝马贵者趣,公交自行程序员。 // 别人笑我忒疯癫,我笑自己命太贱; // 不见满街漂亮妹,哪个归得程序员? import java.io.BufferedReader; import java.io.InputStreamReader; public class Linux { public static Desk getDeskUsage() { Desk desk = new Desk(); try { Runtime rt = Runtime.getRuntime(); Process p = rt.exec("df -hl");// df -hl 查看硬盘空间 BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader( p.getInputStream())); String str = null; String[] strArray = null; int line = 0; while ((str = in.readLine()) != null) { line++; if (line != 2) { continue; } int m = 0; strArray = str.split(" "); for (String para : strArray) { if (para.trim().length() == 0) continue; ++m; if (para.endsWith("G") || para.endsWith("Gi")) { // 目前的服务器 if (m == 2) { desk.setTotal(para); } if (m == 3) { desk.setUsed(para); } } if (para.endsWith("%")) { if (m == 5) { desk.setUse_rate(para); } } } } } catch (Exception e) { e.printStackTrace(); } finally { in.close(); } } catch (Exception e) { e.printStackTrace(); } return desk; } public static class Desk { private String total; private String used; private String use_rate; public String toString(){ return "总磁盘空间:"+total+",已使用:"+used+",使用率达:"+use_rate; } public String getTotal() { return total; } public void setTotal(String total) { this.total = total; } public String getUsed() { return used; } public void setUsed(String used) { this.used = used; } public String getUse_rate() { return use_rate; } public void setUse_rate(String use_rate) { this.use_rate = use_rate; } } public static void main(String[] args) { System.out.println(getDeskUsage()); // 打印结果,博主的电脑是mac,所以显示Gi // 总磁盘空间:234Gi,已使用:100Gi,使用率达:44% } }
版权属于: 技术客
原文地址: https://www.sunjs.com/article/detail/6131d422632f45198c566b17cf18aca9.html
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。