Search code examples
linuxfilesparse-file

How to make file sparse?


If I have a big file containing many zeros, how can i efficiently make it a sparse file?

Is the only possibility to read the whole file (including all zeroes, which may patrially be stored sparse) and to rewrite it to a new file using seek to skip the zero areas?

Or is there a possibility to make this in an existing file (e.g. File.setSparse(long start, long end))?

I'm looking for a solution in Java or some Linux commands, Filesystem will be ext3 or similar.


Solution

  • Some filesystems on Linux / UNIX have the ability to "punch holes" into an existing file. See:

    It's not very portable and not done the same way across the board; as of right now, I believe Java's IO libraries do not provide an interface for this.

    If hole punching is available either via fcntl(F_FREESP) or via any other mechanism, it should be significantly faster than a copy/seek loop.