如何使文件稀疏?

rur*_*uni 8 java linux file sparse-file

如果我有一个包含许多零的大文件,我怎样才能有效地使它成为稀疏文件?

唯一的可能是读取整个文件(包括可能存储稀疏的所有零)并使用seek跳过零区域将其重写为新文件?

或者是否有可能在现有文件中进行此操作(例如File.setSparse(long start,long end))?

我正在寻找Java或某些Linux命令的解决方案,Filesystem将是ext3或类似的.

FeR*_*eRD 5

8年中发生了很多变化。

分配

fallocate -dfilename可用于在现有文件中打孔。从fallocate(1)手册页

       -d, --dig-holes
              Detect and dig holes.  This makes the file sparse in-place,
              without using extra disk space.  The minimum size of the hole
              depends on filesystem I/O block size (usually 4096 bytes).
              Also, when using this option, --keep-size is implied.  If no
              range is specified by --offset and --length, then the entire
              file is analyzed for holes.

              You can think of this option as doing a "cp --sparse" and then
              renaming the destination file to the original, without the
              need for extra disk space.

              See --punch-hole for a list of supported filesystems.
Run Code Online (Sandbox Code Playgroud)

(该列表:)

              Supported for XFS (since Linux 2.6.38), ext4 (since Linux
              3.0), Btrfs (since Linux 3.7) and tmpfs (since Linux 3.5).
Run Code Online (Sandbox Code Playgroud)

我觉得最有趣的是tmpfs。文件系统本身的效率足以仅消耗存储内容所需的RAM,但是使内容稀疏可能会进一步提高效率。

GNU cp

此外,在GNU前进的途中cp,对稀疏文件有了一定的了解。引用cp(1)手册页的默认模式--sparse=auto

稀疏的启发式算法会检测到稀疏的SOURCE文件,并且相应的DEST文件也会变得稀疏。

但是还有--sparse=always,它会激活等效fallocate -d于就地执行的文件复制:

指定--sparse=always在SOURCE文件包含足够长的零字节序列时创建一个稀疏的DEST文件。

我终于可以退休了tar cpSf - SOURCE | (cd DESTDIR && tar xpSf -),这是我20年来一直保留稀疏文件的稀疏方式。

  • 谢谢。你对 GNU cp 的提示对我有帮助。当其他工具(例如“rsync --sparse”)速度慢时,它可以快速工作。 (2认同)

Fra*_*kH. 4

Linux / UNIX 上的某些文件系统具有在现有文件中“打孔”的能力。看:

它不是很便携,也不是全面采用相同的方式;截至目前,我相信 Java 的 IO 库还没有为此提供接口。

如果可以通过或通过任何其他机制进行打孔fcntl(F_FREESP),则它应该比复制/查找循环快得多。