Java编程获取硬盘空间 - 编程入门网
作者 佚名技术
来源 NET编程
浏览
发布时间 2012-06-23
Java编程获取硬盘空间时间:2010-12-06因为论坛有人问到这个问题,所以就写了这篇文章。希望对大家有所帮助。 一般来讲,要用java得到硬盘空间,有3种方法: 1. 调用system的command,然后分析得到的结果,这种方法有很强的系统依赖性,linux下和win下要分别写程序。 下面是一个win下的例子,编译成功之后,运行java Diskspace yourdir(比如c:\) import java.io.BufferedReader; import java.io.InputStreamReader; /** * Determine free disk space for a given directory by * parsing the output of the dir command. * This class is inspired by the code at * Works only under Windows under certain circumstances. * Yes, it''s that shaky. * Requires Java 1.4 or higher. * @[EMAIL PROTECTED] *Marco Schmidt */ public class Diskspace { private Diskspace() { // prevent instantiation of this class } /** * Return available free disk space for a directory. * @[EMAIL PROTECTED] dirName name of the directory * @[EMAIL PROTECTED] free disk space in bytes or -1 if unknown */ public static long getFreeDiskSpace(String dirName) { try { // guess correct ''dir'' command by looking at the // operating system name String os = System.getProperty("os.name"); String command; if (os.equals("Windows NT") ||os.equals("Windows 2000")) { command = "cmd.exe /c dir " + dirName; } else { command = "command.com /c dir " + dirName; } // 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("\\.", ""); freeSpace = freeSpace.replaceAll(",", ""); String[] items = freeSpace.split(" "); // the first valid numeric value in items after(!) index 0 // is probably the free disk space int index = 1; while (index < items.length) { try { long bytes = Long.parseLong(items[index++]); return bytes; } catch (NumberFormatException nfe) { } } return -1; } catch (Exception exception) { return -1; } } /** * Command line program to print the free diskspace to stdout * for all 26 potential root directories A:\ to Z:\ * (when no parameters are given to this progra |
凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢! |
你可能对下面的文章感兴趣
关于Java编程获取硬盘空间 - 编程入门网的所有评论