What is the use of StandardOpenOption.SPARSE?

我的梦境 提交于 2019-12-10 15:43:08

问题


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();
}

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

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.

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.

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

This also creates a sparse file, and I did not have to specify StandardOpenOption.SPARSE at all.

So, what is it used for? Is there any OS/filesystem combination where this option actually influences the behaviour?


回答1:


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).

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.




回答2:


When you use a RandomAccessFile like this on Linux it is Sparse by default on ext4, however if you try ext3 or Windows you may find it is not sparse. i.e. the behaviour of the plain RandomAccessFile constructor is OS dependent.



来源:https://stackoverflow.com/questions/17634362/what-is-the-use-of-standardopenoption-sparse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!