4

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.

Fortega
  • 19,463
  • 14
  • 75
  • 113
  • possible duplicate of [Create file with given size in Java](http://stackoverflow.com/questions/245251/create-file-with-given-size-in-java) – meriton Sep 27 '10 at 12:49

3 Answers3

14

Create a sparse file. That is, open a file, seek to a position above 1GB and write some bytes.

Relevant: Create file with given size in Java

Community
  • 1
  • 1
Sjoerd
  • 74,049
  • 16
  • 131
  • 175
2

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).

Skilldrick
  • 69,215
  • 34
  • 177
  • 229
  • I want to test a piece of code which loads a file from disk based on a filename and does some validation checks. So it has to be a real file. – Fortega Sep 27 '10 at 12:47
1

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