创建大文件的最有效方法(> 1GB)

时间:2010-09-27 12:34:07

标签: java file-io

我想知道在java中创建一个非常大的虚拟文件的最有效方法是什么。 文件大小应该高于1GB。它将用于单元测试只接受文件< = 1GB。

的方法

3 个答案:

答案 0 :(得分:13)

创建稀疏文件。也就是说,打开一个文件,寻找1GB以上的位置并写一些字节。

相关:Create file with given size in Java

答案 1 :(得分:2)

你不能做一个返回>的文件大小的模拟1GB?文件IO对我来说听起来不是很单位(虽然这取决于你对单元测试的看法)。

答案 2 :(得分:0)

使此功能创建稀疏文件

private boolean createSparseFile(String filePath, Long fileSize) {
    boolean success = true;
    String command = "dd if=/dev/zero of=%s bs=1 count=1 seek=%s";
    String formmatedCommand = String.format(command, filePath, fileSize);
    String s;
    Process p;
    try {
        p = Runtime.getRuntime().exec(formmatedCommand);

        p.waitFor();
        p.destroy();
    } catch (IOException | InterruptedException e) {
        fail(e.getLocalizedMessage());
    }
    return success;
}