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

论坛 期权论坛 脚本     
匿名技术用户   2020-12-29 22:27   39   0

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 瞬间快速创建固定大小文件,毫秒级。。。

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP