What is the use of StandardOpenOption.SPARSE?
file-io, filesystems, java, java-7
Solution
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.
Problem
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?