Windows 及 Linux 下如何通过命令生成任意大小的空文件

142次阅读
没有评论

共计 978 个字符,预计需要花费 3 分钟才能阅读完成。

Linux

dd 命令:

+ View code

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

 

生成 50 MB 的空文件:

+ View code

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

 

Windows

fsutil 命令:

+ View code

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

 

生成 10MB 的空文件:

+ View code

fsutil file createnew 10M-1.txt 10485760

 

Java

用 FileChannel 的 write 方法:

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

Windows 及 Linux 下如何通过命令生成任意大小的空文件+ View code

    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();
            }
        }
    }

Windows 及 Linux 下如何通过命令生成任意大小的空文件

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

Windows 及 Linux 下如何通过命令生成任意大小的空文件+ View code

   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();
            }
        }
   }

Windows 及 Linux 下如何通过命令生成任意大小的空文件

参考资料:

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

正文完
 
admin
版权声明:本站原创文章,由 admin 2020-01-13发表,共计978字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)
验证码