在Java中查找总磁盘大小的便携方式(前java 6) [英] Portable way of finding total disk size in Java (pre java 6)

查看:147
本文介绍了在Java中查找总磁盘大小的便携方式(前java 6)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在Java 5(或1.5,无论如何)中找到驱动器的总大小。我知道Java 6在java.io.File中有一个新方法,但我需要它在Java 5中工作。

I need to find the total size of a drive in Java 5 (or 1.5, whatever). I know that Java 6 has a new method in java.io.File, but I need it to work in Java 5.

Apache Commons IO有org.apache.commons .io.FileSystemUtils提供 free 磁盘空间,但不提供总磁盘空间。

Apache Commons IO has org.apache.commons.io.FileSystemUtils to provide the free disk space, but not the total disk space.

我意识到这是依赖于操作系统的,需要依赖凌乱的命令行调用。我很喜欢它在大多数系统上工作,即windows / linux / macosx。我最好使用现有的库而不是编写自己的变体。

I realize this is OS dependant and will need to depend on messy command line invocation. I'm fine with it working on "most" systems, i.e. windows/linux/macosx. Preferably I'd like to use an existing library rather than write my own variants.

有什么想法吗?谢谢。

推荐答案

更新:

我为误读问题而道歉,我建议复制FileSystemUtils方法,但修改它稍微运行的命令。

I apologise for misreading the question, I recommend copying the FileSystemUtils approach, but modifying the commands it runs slightly.

在dos中,你可以使用fsutil命令获得空闲和总字节数:

In dos you can get the free and total bytes with the fsutil command:

fsutil volume diskfree [drive letter]

在我的方框中,这给出了以下结果:

on my box this gives the following results:

Total # of free bytes        : 41707524096
Total # of bytes             : 80023715840
Total # of avail free bytes  : 41707524096

在Unix上,命令仍为df -k,您只对Free左侧的1024-blocks列感兴趣(下面的Wikipedia示例)。你显然需要将结果乘以1024.

On Unix, the command is still "df -k", you're just interested in the "1024-blocks" column to the left of "Free" (example from Wikipedia below). You obviously need to multiply the result by 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()委托等效的特定于操作系统的方法。 Windows的实现将是这样的(请注意使用查找来修剪fsutil的输出以获得总大小):

Assuming you copy FileSystemUtils to implement "totalSpaceKB()" to delegate to an equivalent OS-specific method. The implementation for Windows would be something like this (note the use of "Find" to trim the output from fsutil to just get the total size):

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()的两次调用

The implementation for Unix would be the same as freeSpaceUnix(), but remove the two calls to tok.nextToken() at the end of the method

    /** 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);
}

其他平台的实现方式类似。

The implementations for other platforms would be similar.

希望这有助于为误读而道歉问题。

Hope this helps and apologies agian for misreading the problem.

原始答案(获得免费字节,而不是总数)。

在Java 6之前,没有一种优雅的方法可以做到这一点,(参见 bug )。我建议您使用库来为您执行特定于平台的处理,而不是滚动自己。

Prior to Java 6 there isn't an elegant way to do this, (see the bug). Rather than rolling your own, I'd recommend using a library to do the platform-specific processing for you.

Apache commons-io 有一个 FileSystemUtils 类型,提供静态方法freeSpaceKb()。它适用于Windows和一些Unix实现(参见下面的Javadoc引用)

Apache commons-io has a FileSystemUtils type that provides a static method freeSpaceKb(). It works on Windows and and some Unix implementations (see quote from Javadoc below)

来自Javadoc:


public static long freeSpaceKb(String path)
throws IOException

public static long freeSpaceKb(String path) throws IOException

通过调用,返回驱动器或卷上的可用空间(以KB为单位)命令行。
FileSystemUtils.freeSpaceKb(C:); // Windows
FileSystemUtils.freeSpaceKb(/ volume); // * nix

Returns the free space on a drive or volume in kilobytes by invoking the command line. FileSystemUtils.freeSpaceKb("C:"); // Windows FileSystemUtils.freeSpaceKb("/volume"); // *nix

可用空间通过命令行计算。它在Windows上使用'dir / -c',在AIX / HP-UX上使用'df -kP',在其他Unix上使用'df -k'。
为了工作,您必须运行Windows,或者在传递-k(或-kP)时使用支持GNU格式的Unix df实现。如果您要依赖此代码,请通过运行一些简单的测试来检查它是否适用于您的操作系统,以将命令行与此类的输出进行比较。如果您的操作系统不受支持,请提出一个JIRA电话,详细说明df -k的确切结果以及尽可能多的其他细节,谢谢。

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.

这篇关于在Java中查找总磁盘大小的便携方式(前java 6)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆