Dio*_*lis 94
创建一个新的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);
}
}
Run Code Online (Sandbox Code Playgroud)
在Linux机器上将使用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
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
在这两种情况下,这将导致创建稀疏文件.
小智 5
从 Java 8 开始,此方法适用于 Linux 和 Windows:
final ByteBuffer buf = ByteBuffer.allocate(4).putInt(2);
buf.rewind();
final OpenOption[] options = { StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW , StandardOpenOption.SPARSE };
final Path hugeFile = Paths.get("hugefile.txt");
try (final SeekableByteChannel channel = Files.newByteChannel(hugeFile, options);) {
channel.position(HUGE_FILE_SIZE);
channel.write(buf);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
37840 次 |
| 最近记录: |