创建大于1GB的文件的最有效方法

4
我想知道在Java中创建一个非常大的虚拟文件的最有效方法。 文件大小应该略大于1GB。它将用于对只接受文件<= 1GB的方法进行单元测试。

可能是在Java中创建指定大小的文件的重复问题。 - meriton
3个回答

14

2

你能不能创建一个返回文件大小大于1GB的模拟?对我来说,文件IO听起来不太像单元测试(尽管这取决于你对单元测试的理解)。


我想测试一段代码,它根据文件名从磁盘加载文件并进行一些验证检查。因此,它必须是一个真实的文件。 - Fortega

1
制作了这个函数来创建稀疏文件。
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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接