Java、Linux、Win 快速生成指定大小的空文件

Linux

dd 命令:

dd if=/dev/zero of=<fileName> bs=<一次复制的大小> count=<复制的次数>

生成 50 MB 的空文件:

dd if=/dev/zero of=50M-1.txt bs=1M count=50

Windows

fsutil 命令:

fsutil file createnew <fileName> <文件大小单位字节>

生成 10MB 的空文件:

fsutil file createnew 10M-1.txt 10485760

Java

用 FileChannel 的 write 方法:

在指定位置插入一个空字符,这个指定的位置下标即生成目标文件的大小,单位为字节

    private static void createFixLengthFile(File file, long length) throws IOException {
        FileOutputStream fos = null;
        FileChannel outC = null;
        try {
            fos = new FileOutputStream(file);
            outC = fos.getChannel();
            // 从给定的文件位置开始,将字节序列从给定缓冲区写入此通道
            // ByteBuffer.allocate 分配一个新的字节缓冲区
            outC.write(ByteBuffer.allocate(1), length - 1);
        } finally {
            try {
                if (outC != null) {
                    outC.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

第二种,用 RandomAccessFile 的 setLength 方法更为方便:

   private static void createFile(File file, long length) throws IOException {
        RandomAccessFile r = null;
        try {
            r = new RandomAccessFile(file, "rw");
            r.setLength(length);
        } finally {
            if (r != null) {
                r.close();
            }
        }
   }

参考资料:

java 瞬间快速创建固定大小文件,毫秒级。。。

原文地址:https://www.cnblogs.com/zhengbin/p/8421519.html