Java 预分配文件空间

内容纲要

介绍

通常我们为了文件在磁盘块上的连续性,我们需要为文件预分配或者动态扩展很多块,这样可以提升写文件的性能。
通常文件系统也会为我们的文件在磁盘块上预留几个连续的磁盘块,这样可以提供文件写的性能,但是文件系统的预留页机制不一定能够满足我们的需求,所以我们可以根据自己的业务特性为文件预留连续的磁盘块。
在Java中为文件预分配空间通常有两种方式(这两种方式都和RandomAccessFile有关):

  1. 文件映射
  2. 真实写文件

文件映射

File file = new File("demo");
FileChannel fileChannel = new RandomAccessFile(file, "rw").getChannel();
MappedByteBuffer mappedByteBuffer = fileChannel.map(MapMode.READ_WRITE, 0, fileSize);

写文件

代码如下:

/**
 * 文件预分配工具类
 * 参考zookeeper FilePadding 实现
 * @author errorfatal89@gmail.com
 * @datetime 2022/03/25 11:54
 */
public class FilePaddingUtil {

    private static final ByteBuffer FILL = ByteBuffer.allocateDirect(1);

    /**
     * 预分配文件
     * @param fileChannel fileChannel
     * @param toPos 起始偏移
     * @throws IOException 
     */
    public static void padFile(FileChannel fileChannel, long toPos) throws IOException {
        fileChannel.write((ByteBuffer) FILL.position(0), toPos);
    }
}
// 调用方式
rasFile = new RandomAccessFile(file, "rw");
FileChannel fileChannel = rasFile.getChannel();

参考

  1. Zookeeper PadFile实现

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注

滚动至顶部