更新:
我很抱歉误读了这个问题,我建议复制FileSystemUtils方法,但修改稍微运行的命令。
在dos中,您可以使用fsutil命令获取可用字节和总字节数:
fsutil volume diskfree [drive letter]在我的盒子上,这给出了以下结果:
Total # of free bytes : 41707524096
Total # of bytes : 80023715840
Total # of avail free bytes : 41707524096在Unix上,该命令仍然是“df -k”,你只是对“Free”左边的“1024-blocks”列感兴趣(例如下面的维基百科)。你显然需要乘以1024的结果。
Filesystem 1024-blocks Free %Used Iused %Iused Mounted on
/dev/hd4 32768 16016 52% 2271 14% /
/dev/hd2 4587520 1889420 59% 37791 4% /usr
/dev/hd9var 65536 12032 82% 518 4% /var
/dev/hd3 819200 637832 23% 1829 1% /tmp
/dev/hd1 524288 395848 25% 421 1% /home
/proc - - - - - /proc
/dev/hd10opt 65536 26004 61% 654 4% /opt假设您复制FileSystemUtils以实现“totalSpaceKB()”以委托给等效的特定于OS的方法。 Windows的实现将是这样的(注意使用“Find”来修剪fsutil的输出以获得总大小):
long totalSpaceWindows(String path) throws IOException {
path = FilenameUtils.normalize(path);
if (path.length() > 2 && path.charAt(1) == ':') {
path = path.substring(0, 2); // seems to make it work
}
// build and run the 'fsutil' command
String[] cmdAttribs = new String[] {
"cmd.exe",
"/C",
"fsutil volume diskfree " + path
+ " | Find \"Total # of bytes\"" };
// read in the output of the command to an ArrayList
List lines = performCommand(cmdAttribs, Integer.MAX_VALUE);
//because we used Find, we expect the first line to be "Total # of bytes",
//you might want to add some checking to be sure
if (lines.size() > 0) {
String line = (String) lines.get(0);
String bytes = line.split(":")[1].trim();
return Long.parseLong(bytes);
}
// all lines are blank
throw new IOException(
"Command line 'fsutil volume diskfree' did not return
+ "any info for path '" + path + "'");
}Unix的实现将与freeSpaceUnix()相同,但是在方法结束时删除对tok.nextToken()的两个调用
/** comment these two lines so the token received is the total size */
tok.nextToken(); // Ignore 1K-blocks
tok.nextToken(); // Ignore Used
/** this will now be the total size */
String freeSpace = tok.nextToken();
return parseBytes(freeSpace, path);
}其他平台的实现类似。
希望这有助于并理解误解问题。
原始答案(获得空闲字节,不是全部)。
在Java 6之前,没有一种优雅的方式来实现这一点,(请参阅bug)。我建议使用一个库来为您执行特定于平台的处理,而不是自己动手。
Apache commons-io具有提供静态方法freeSpaceKb()的FileSystemUtils类型。它适用于Windows和一些Unix实现(请参阅下面的Javadoc的引用)
从Javadoc:
public static long freeSpaceKb(String path)
throws IOException
Returns the free space on a drive or volume in kilobytes by invoking the command line.
FileSystemUtils.freeSpaceKb("C:"); // Windows
FileSystemUtils.freeSpaceKb("/volume"); // *nix
The free space is calculated via the command line. It uses 'dir /-c' on Windows, 'df -kP' on AIX/HP-UX and 'df -k' on other Unix.
In order to work, you must be running Windows, or have a implementation of Unix df that supports GNU format when passed -k (or -kP). If you are going to rely on this code, please check that it works on your OS by running some simple tests to compare the command line with the output from this class. If your operating system isn't supported, please raise a JIRA call detailing the exact result from df -k and as much other detail as possible, thanks.