Skip to main content
  1. blog/

Create a file with a specific size in Java

··1 min

Note

This article was written over 5 years ago. Some information may be outdated or irrelevant.

Overview #

The java.io package offers classes that help us create and manage files. In this article, I’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 #

1
2
3
4
5
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 3.

Create a file with a specific size #

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

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
private File createFile(final String filename, final long sizeInBytes) throws IOException {
 File file = new File(filename);
  file.createNewFile();
  
  try (RandomAccessFile raf = new RandomAccessFile(file, "rw")) {
    raf.setLength(sizeInBytes);
  }
  
  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.