JAVA查看本地磁盘空间大小
利用java获取本地磁盘空间大小
public class FileUtil {
public static long getFreeDiskSpace(String dirName) throws Exception{
//如果目录不存在
File dir = new File(dirName);
if(!dir.exists()) return -1;
try{
// guess correct \'dir\' command by looking at the
// operating system name
String os = System.getProperty("os.name");
String command;
if ("Windows NT".equals(os) || "Windows 2000".equals(os) || "Windows 2003".equals(os) || "Windows XP".equals(os) ){
command = "cmd.exe /c dir " + dir.getAbsolutePath();
}else{
return -1;
}
logger.debug(command);
// 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("[\\.|,]", "");
String[] items = freeSpace.split(" ");
// the first valid numeric value in items after(!) index 0
// is probably the free disk space
//obtain dir usable byte
int index = 1;
while (index < items.length) {
try{
long bytes = Long.parseLong(items[index++]);
return bytes;
}catch (NumberFormatException nfe){}
}
return -1;
}
catch (Exception e){
throw e;
}
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
System.out.println(getFreeDiskSpace("E:/"));
}
}
参考文章:http://tech.ccidnet.com/art/3737/20040710/468701_1.html
以上是 JAVA查看本地磁盘空间大小 的全部内容, 来源链接: utcz.com/z/389998.html