在Java中创建给定大小的文件 [英] Create file with given size in Java

查看:348
本文介绍了在Java中创建给定大小的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中创建具有给定大小的文件是否具有高效的方式?



在C中可以使用 ftruncate (请参阅那个答案)。



大多数人只会将 n 虚拟字节写入文件,但必须有更快的方式。我正在考虑 ftruncate 以及稀疏文件 ...

解决方案

创建一个新的 RandomAccessFile 并调用setLength方法,指定所需的文件长度。基本的JRE实现应该使用您环境中最有效的方法。



以下程序

  import java.io. *; 

class Test {
public static void main(String args [])throws Exception {
RandomAccessFile f = new RandomAccessFile(t,rw);
f.setLength(1024 * 1024 * 1024);
}
}

在Linux机器上将使用ftruncate分配空间(2)

  6070 open(t,O_RDWR | O_CREAT,0666)= 4 
6070 fstat ,{st_mode = S_IFREG | 0644,st_size = 0,...})= 0
6070 lseek(4,0,SEEK_CUR)= 0
6070 ftruncate(4,1073741824)= 0

而在Solaris机器上,它将使用fcntl(2)系统调用的F_FREESP64函数。 >

  / 2:open64(t,O_RDWR | O_CREAT,0666)= 14 
/ 2:fstat64(14,0xFE4FF810 )= 0
/ 2:llseek(14,0,SEEK_CUR)= 0
/ 2:fcntl(14,F_FREESP64,0xFE4FF998)= 0
pre>

在这两种情况下,这将导致创建一个稀疏文件。


Is there an efficient way to create a file with a given size in Java?

In C it can be done with ftruncate (see that answer).

Most people would just write n dummy bytes into the file, but there must be a faster way. I'm thinking of ftruncate and also of Sparse files

解决方案

Create a new RandomAccessFile and call the setLength method, specifying the desired file length. The underlying JRE implementation should use the most efficient method available in your environment.

The following program

import java.io.*;

class Test {
     public static void main(String args[]) throws Exception {
           RandomAccessFile f = new RandomAccessFile("t", "rw");
           f.setLength(1024 * 1024 * 1024);
     }
}

on a Linux machine will allocate the space using the ftruncate(2)

6070  open("t", O_RDWR|O_CREAT, 0666)   = 4
6070  fstat(4, {st_mode=S_IFREG|0644, st_size=0, ...}) = 0
6070  lseek(4, 0, SEEK_CUR)             = 0
6070  ftruncate(4, 1073741824)          = 0

while on a Solaris machine it will use the the F_FREESP64 function of the fcntl(2) system call.

/2:     open64("t", O_RDWR|O_CREAT, 0666)               = 14
/2:     fstat64(14, 0xFE4FF810)                         = 0
/2:     llseek(14, 0, SEEK_CUR)                         = 0
/2:     fcntl(14, F_FREESP64, 0xFE4FF998)               = 0

In both cases this will result in the creation of a sparse file.

这篇关于在Java中创建给定大小的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆