问题描述
Java 7 定义此选项,但我仍然无法理解它的用处.请考虑这个简单的程序,该程序可以在具有Java 6 JVM的最新的Linux计算机上运行:
Java 7 defines this option, yet I fail to understand its usefulness.Consider this simple program, run on a recent enough Linux machine, with a Java 6 JVM:
public static void main(final String... args)
throws IOException
{
final long offset = 1L << 31;
final RandomAccessFile f = new RandomAccessFile("/tmp/foo", "rw");
f.seek(offset);
f.writeInt(2);
f.close();
}
当我查询文件"shell wise"时,我得到了预期的结果:
When I query the file "shell wise", I get, as expected:
$ cd /tmp
$ stat --format %s foo
2147483652
$ du --block-size=1 foo
4096 foo
也就是说,inode真实地声明该文件的大小接近2 GB,但由于基础fs的块大小为4k,因此其磁盘使用情况实际上是一个块.好.
That is, the inode truthfully declares that the file has a size close to 2 GB, but its disk usage is in fact a single block since the underlying fs has a 4k block size. Good.
但是我不需要Java 7的StandardOpenOption.SPARSE
.实际上,如果我使用Java 7 JVM运行完全相同的代码,结果将不会改变.
But I didn't need Java 7's StandardOpenOption.SPARSE
for that. In fact, if I run this exact same code with a Java 7 JVM, the results do not vary.
现在,进入一些仅Java 7的代码:
Now, on to some Java 7-only code:
public static void main(final String... args)
throws IOException
{
final ByteBuffer buf = ByteBuffer.allocate(4).putInt(2);
buf.rewind();
final OpenOption[] options = {
StandardOpenOption.WRITE,
StandardOpenOption.CREATE_NEW
};
final Path path = Paths.get("/tmp/foo");
Files.deleteIfExists(path);
try (
final SeekableByteChannel channel
= Files.newByteChannel(path, options);
) {
channel.position(1L << 31);
channel.write(buf);
}
}
此还创建了一个稀疏文件,我完全不必指定StandardOpenOption.SPARSE
.
This also creates a sparse file, and I did not have to specify StandardOpenOption.SPARSE
at all.
那么,它的作用是什么?是否有任何OS/文件系统组合会真正影响该行为?
So, what is it used for? Is there any OS/filesystem combination where this option actually influences the behaviour?
推荐答案
I/O教程将NTFS列为该选项很重要的一个文件系统. 稀疏文件支持中的Microsoft文档NTFS 说,稀疏文件必须明确标记为稀疏,并且列出了稀疏文件特有的操作(将区域归零,使用非零数据搜索范围等).
Oracle's notes in the I/O tutorial list NTFS as one filesystem in which the option matters. Microsoft's docs on sparse file support in NTFS says that sparse files must be explicitly marked as sparse, and it lists actions specific to sparse files (zeroing out regions, searching for ranges with non-zero data, etc).
我没有方便尝试的Windows框,但是看到这些教程专门调出了NTFS,这可能是一个集中搜索的地方.
I don't have a Windows box handy on which to try this out, but seeing as the tutorials specifically call out NTFS, that might be a place to focus the search.
这篇关于StandardOpenOption.SPARSE的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!