在Java中获取文件的实际磁盘使用情况 [英] Get actual disk usage for a file in java

查看:389
本文介绍了在Java中获取文件的实际磁盘使用情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用java.io.File.length()方法获取文件的大小.

I am using java.io.File.length() method to get size of a file.

但是对于稀疏文件,此值可能与该文件使用的实际磁盘空间有很大差异.

But for a sparse file this value can be very different from actual disk space used by that file.

是否可以获取文件的实际磁盘使用情况?

Is there a way to get actual disk usage for the file?

文件的外观大小是文件中的字节数.例如,一个包含单词"zoo"且没有换行符的文件的大小显然为3.但是,使用以下命令创建的稀疏文件:

The apparent size of a file is the number of bytes in a file. For example, a file containing the word ‘zoo’ with no newline would, of course, have an apparent size of 3. However, a sparse file created with this command:

dd bs=1 seek=2GiB if=/dev/null of=big

表面上的大小为2 GiB,但是在大多数现代系统上,它实际上几乎不占用磁盘空间.

has an apparent size of 2 GiB, yet on most modern systems, it actually uses almost no disk space.

推荐答案

使用 jnr-posix .用法示例:

import jnr.posix.*;

final POSIX p = POSIXFactory.getPOSIX();
final int S_BLKSIZE = 512; // from sys/stat.h
final FileStat stat = p.stat("/some/file.txt");
final long bytes = stat.blocks() * S_BLKSIZE;

这篇关于在Java中获取文件的实际磁盘使用情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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