Home » Core Java » io » File » Create new empty file

About Ilias Tsagklis

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

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;

import java.io.File;
import java.io.IOException;

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.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

 

Leave a Reply

avatar
  Subscribe  
Notify of