Java – Create a File

1. Overview

In this quick tutorial, we’re going to learn how to create a new File in Java – first using the Files and Path classes from NIO, then the Java File and FileOutputStream classes, Google Guava, and finally the Apache Commons IO library.

This article is part of the “Java – Back to Basic” series here on VietMX’s Blog.

2. Setup

In the examples, we’ll define a constant for the file name:

private final String FILE_NAME = "src/test/resources/fileToCreate.txt";

And we’ll also add a clean-up step to make sure that the file doesn’t already exist before each test, and to delete it after each test runs:

@AfterEach
@BeforeEach
public void cleanUpFiles() {
    File targetFile = new File(FILE_NAME);
    targetFile.delete();
}

3. Using NIO Files.createFile()

Let’s start by using the Files.createFile() method from the Java NIO package:

@Test
public void givenUsingNio_whenCreatingFile_thenCorrect() throws IOException {
    Path newFilePath = Paths.get(FILE_NAME);
    Files.createFile(newFilePath);
}

As you can see the code is still very simple; we’re now using the new Path interface instead of the old File.

One thing to note here is that the new API makes good use of exceptions. If the file already exists, we no longer have to check a return code. Instead, we’ll get a FileAlreadyExistsException:

java.nio.file.FileAlreadyExistsException: src/test/resources/fileToCreate.txt
at sun.n.f.WindowsException.translateToIOException(WindowsException.java:81)

4. Using File.createNewFile()

Let’s now look at how we can do the same using the java.io.File class:

@Test
public void givenUsingFile_whenCreatingFile_thenCorrect() throws IOException {
    File newFile = new File(FILE_NAME);
    boolean success = newFile.createNewFile();
    assertTrue(success);
}

Note that the file must not exist for this operation to succeed. If the file does exist, then the createNewFile() operation will return false.

5. Using FileOutputStream

Another way to create a new file is to use the java.io.FileOutputStream:

@Test
public void givenUsingFileOutputStream_whenCreatingFile_thenCorrect() throws IOException {
    try(FileOutputStream fileOutputStream = new FileOutputStream(FILE_NAME)){
    }
}

In this case, a new file is created when we instantiate the FileOutputStream object. If a file with a given name already exists, it will be overwritten. If, however, the existing file is a directory or a new file cannot be created for any reason, then we’ll get a FileNotFoundException.

Additionally, note we used a try-with-resources statement – to be sure that a stream is properly closed.

6. Using Guava

The Guava solution for creating a new file is a quick one-liner as well:

@Test
public void givenUsingGuava_whenCreatingFile_thenCorrect() throws IOException {
    com.google.common.io.Files.touch(new File(FILE_NAME));
}

7. Using Apache Commons IO

The Apache Commons library provides the FileUtils.touch() method which implements the same behavior as the “touch” utility in Linux.

Therefore it creates a new empty file or even a file and the full path to it in a file system:

@Test
public void givenUsingCommonsIo_whenCreatingFile_thenCorrect() throws IOException {
    FileUtils.touch(new File(FILE_NAME));
}

Note that this behaves slightly differently than the previous examples: if the file already exists, the operation doesn’t fail, it simply doesn’t do anything.

And there we have it – 4 quick ways to create a new file in Java.

8. Conclusion

In this article, we looked at different solutions for creating a file in Java. We used classes that are part of the JDK and external libraries.

The code for the examples is available over on GitHub.

Related posts:

Java Program for Douglas-Peucker Algorithm Implementation
Hướng dẫn Java Design Pattern – Service Locator
Java Scanner hasNext() vs. hasNextLine()
Spring Boot Application as a Service
Ép kiểu trong Java (Type casting)
Java Program to Use the Bellman-Ford Algorithm to Find the Shortest Path
Java Program to Use Dynamic Programming to Solve Approximate String Matching
Java Program to Implement Hash Tables with Linear Probing
Split a String in Java
Mảng (Array) trong Java
Validate email address exists or not by Java Code
Java Program to Implement LinkedBlockingDeque API
Kiểu dữ liệu Ngày Giờ (Date Time) trong java
Java Program to Find the Edge Connectivity of a Graph
Most commonly used String methods in Java
Java Program to Generate Random Numbers Using Probability Distribution Function
Serverless Functions with Spring Cloud Function
Java Program to Implement the One Time Pad Algorithm
Summing Numbers with Java Streams
Java Program to Implement the linear congruential generator for Pseudo Random Number Generation
Java Program to Implement Min Heap
Java Concurrency Interview Questions and Answers
Hướng dẫn Java Design Pattern – Transfer Object
Quản lý bộ nhớ trong Java với Heap Space vs Stack
Spring’s RequestBody and ResponseBody Annotations
Hướng dẫn Java Design Pattern – Singleton
Java Program to Implement Bresenham Line Algorithm
Registration – Activate a New Account by Email
A Quick Guide to Spring MVC Matrix Variables
Java Program to Implement Gale Shapley Algorithm
Java Program to Implement the Edmond’s Algorithm for Maximum Cardinality Matching
Tránh lỗi NullPointerException trong Java như thế nào?