java 创建大文件(> 1GB)的最有效方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3803775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Most efficient way to create a large file (> 1GB)
提问by Fortega
I would like to know what is the most efficient way to create a very large dummy File in java. The filesize should be just above 1GB. It will be used to unit test a method which only accepts files <= 1GB.
我想知道在 java 中创建一个非常大的虚拟文件的最有效方法是什么。文件大小应略高于 1GB。它将用于对仅接受 <= 1GB 文件的方法进行单元测试。
回答by Sjoerd
Create a sparse file. That is, open a file, seek to a position above 1GB and write some bytes.
创建一个稀疏文件。也就是说,打开一个文件,寻找 1GB 以上的位置并写入一些字节。
Relevant: Create file with given size in Java
回答by Skilldrick
Can't you make a mock which returns filesize of > 1GB? File IO doesn't sound very unit-testy to me (although that depends on what your idea of a unit test is).
你不能做一个返回> 1GB文件大小的模拟吗?文件 IO 对我来说听起来不是很单元测试(尽管这取决于您对单元测试的想法)。
回答by Philip Menke
Made this function to create sparse files
使此功能创建稀疏文件
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;
}