代码之家  ›  专栏  ›  技术社区  ›  Fortega

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

  •  1
  • Fortega  · 技术社区  · 14 年前

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

    3 回复  |  直到 9 年前
        1
  •  13
  •   Community CDub    7 年前

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

    相关: Create file with given size in Java

        2
  •  2
  •   Skilldrick    14 年前

    您不能模拟返回文件大小为1GB的文件吗?对我来说,文件IO听起来不是很单元测试(尽管这取决于您对单元测试的想法)。

        3
  •  0
  •   Philip Menke    9 年前

    使用此函数创建稀疏文件

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