java 磁盘_Java获取磁盘大小

我们在网上查找获取磁盘大小的程序时,经常会见到这样的程序,windows是一套写法(用java的api),linux是一套写法(用的是模拟命令行运行命令的方式获取磁盘空间)。所以我们想当然的以为,windows的写法在linux上行不通。一般的写法如下:

package com.example.demo.TypeTest;

import java.io.File;

import java.io.InputStreamReader;

import java.io.LineNumberReader;

/**

*@Description: TODO

*@Author: xushu

*@Date: 2019-10-23 14:34

**/

public class Test {

/**

* 执行系统命令

*

* @param cmd 命令

* @return 字符串结果

*/

private static String runCommand(String cmd) {

StringBuilder info = new StringBuilder();

try {

Process pos = Runtime.getRuntime().exec(cmd);

pos.waitFor();

InputStreamReader isr = new InputStreamReader(pos.getInputStream());

LineNumberReader lnr = new LineNumberReader(isr);

String line;

while ((line = lnr.readLine()) != null) {

info.append(line).append("\n");

}

} catch (Exception e) {

info = new StringBuilder(e.toString());

}

return info.toString();

}

/**

* 判断系统是否为windows

*

* @return 是否

*/

private static boolean isWindows() {

return System.getProperties().getProperty("os.name").toUpperCase().contains("WINDOWS");

}

private static final String path = "D:/FileFromFtp";

/**

* 判断是否需要删除文件

*

* @return 磁盘使用率

*/

public static boolean getWinDiskStoresInfo() {

//系统为windows

if(isWindows()) {

String dirName = path.substring(0, path.indexOf("/") + 1);

File win = new File(dirName);

if (win.exists()) {

long total = win.getTotalSpace();

long usableSpace = win.getUsableSpace();

if((double)(total - usableSpace) / total > 0.8){

return true;

}

}

}else {

//系统为Unix

String ioCmdStr = "df -h /";

String resultInfo = runCommand(ioCmdStr);

String[] data = resultInfo.split(" +");

double total = Double.parseDouble(data[10].replace("%", ""));

if(total / 100 > 0.8){

return true;

}

}

return false;

}

public static void main(String[] args) throws NoSuchFieldException {

getWinDiskStoresInfo();

}

}

其实这样好蛋疼,我也不知道这是什么瞎几把写法,好多人都不知道思考或者实验一下,拿起代码就是抄。Java在windows平台上实现了一套文件系统,为WinNTFileSystem,它支持获取目标卷的总容量和剩余容量。那么在linux上,它同样实现了一套文件系统,为UnixFileSystem,所以,不管什么平台,只需要统一的写法。所以写法可以省略为:

package com.example.demo.TypeTest;

import java.io.File;

/**

*@Description: TODO

*@Author: xushu

*@Date: 2019-10-24 10:59

**/

public class BBB {

public static void main(String[] args) {

File win = new File("/");

if (win.exists()) {

long total = win.getTotalSpace();

long usableSpace = win.getUsableSpace();

System.out.println((double)(total - usableSpace) / total);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值