Create new empty file

This is an example of how to create a new empty File. We are using the File class that is an abstract representation of file and directory pathnames. Creating a new empty file implies that you should:

  • Create a new File instance by converting the given pathname string into an abstract pathname.
  • Use createNewFile() API method of File. This method atomically creates a new, empty file named by this abstract pathname if and only if a file with this name does not yet exist. The check for the existence of the file and the creation of the file if it does not exist are a single operation that is atomic with respect to all other filesystem activities that might affect the file.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;


public class CreateNewEmptyFile {

	public static void main(String[] args) {

		File file = new File("C://test.txt");

		boolean fileCreated = false;
		try {
			fileCreated = file.createNewFile();
		catch (IOException ioe) {
			System.out.println("Error while creating empty file: " + ioe);

		if (fileCreated) {
			System.out.println("Created empty file: " + file.getPath());
		else {
			System.out.println("Failed to create empty file: " + file.getPath());

This was an example of how to create a new empty File in Java.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!


1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design


and many more ....


Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions


Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button