I've created this method to generate Files with random content.
Memory consumption is minimal, as we do not keep the whole file in memory, but write it to the disk through an 8K buffer.
The file will be in the system's temp folder, and will be deleted automatically when the JVM stops. (I use it in tests only, but can be modified if auto cleanup is not necessary.)
An example usage: generateFile(ofGigabytes(2))
. (If you don't use spring, just use long instead of DataSize class as the function argument).
import lombok.SneakyThrows;
import org.jetbrains.annotations.NotNull;
import org.springframework.util.unit.DataSize;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Random;
import static org.springframework.util.unit.DataSize.ofKilobytes;
public class DocumentTestUtil {
private static final long DEFAULT_BUFFER_SIZE = ofKilobytes(8).toBytes();
private DocumentTestUtil() {
}
@SneakyThrows
public static @NotNull File generateFile(DataSize size) {
File file = File.createTempFile("test-document-", null);
file.deleteOnExit();
try (final var os = new BufferedOutputStream(new FileOutputStream(file))) {
long numOfBytes = 0;
final var bytes = new byte[calculateBufferSize(size)];
final var random = new Random();
while (numOfBytes < size.toBytes()) {
random.nextBytes(bytes);
os.write(bytes);
numOfBytes += bytes.length;
}
}
return file;
}
private static int calculateBufferSize(final DataSize size) {
if (size.toBytes() > DEFAULT_BUFFER_SIZE) {
return (int) DEFAULT_BUFFER_SIZE;
}
return (int) size.toBytes();
}
}
dd if=/dev/urandom of=random.txt bs=4096 count=512
(4096 * 512 = 2meg, adjust as needed for your 2gig). – Bazemore