Create a File with a Specific Size in Java

Overview

The java.io package offers classes that help us create and manage files. In this article, we’ll demonstrate how to create an empty file based on a filename and how to create a file with a certain size.

Code Examples

Create an empty file

private File createFile(final String filename) throws IOException {
  File file = new File(filename);
  file.createNewFile();
  return file;
}

Note that this does not create missing parent folders. If you need to do this, call file.getParentFile().mkdirs() on line 2.

Create a file with a specific size

We can use the RandomAccessFile class to create a file with a specific size.

private File createFile(final String filename, final long sizeInBytes) throws IOException {
  File file = new File(filename);
  file.createNewFile();
  
  RandomAccessFile raf = new RandomAccessFile(file, "rw");
  raf.setLength(sizeInBytes);
  raf.close();
  
  return file;
}

Note that files created this way are populated with random data and may be treated as "sparse files" by the JVM implementation and the underlying operating system.