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.
            Asked
            
        
        
            Active
            
        
            Viewed 1.6k times
        
    3 Answers
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
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;
}
        Philip Menke
        
- 45
 - 4