File

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.

Ilias Tsagklis

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

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

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button