Java File createNewFile() method example

HQ ┬╗ Java Tutorial ┬╗ java.io ┬╗ File ┬╗ createNewFile() method example
Java File createNewFile() method example 2018-02-16T07:26:44+00:00

java.io.File createNewFile()

Description

On this document we will be showing a java example on how to use the createNewFile() method of File Class. This method is basically in place to 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.

Throws:

  • IOException – If an I/O error occurred
  • SecurityException – If a security manager exists and its SecurityManager.checkWrite(java.lang.String) method denies write access to the file

Method Syntax

public boolean createNewFile() throws IOException

Method Argument

Data Type Parameter Description
N/A N/A N/A

Method Returns

This method returns boolean, true if the named file does not exist and was successfully created; false if the named file already exists. This is in place so that you have a way to determine if the creation of file is successful or not and act accordingly.

Compatibility

Requires Java 1.2 and up

Java File createNewFile() Example

Below is a java code demonstrates the use of createNewFile() method of File class. The example presented might be simple however it shows the behaviour of the createNewFile() method of File class. Basically we called this method and we put a check on the returned value to check if the creation of new file is successful or not.

The example provided below shows that on the first run, the file has been created successfully while on the second run it failed. That is because the file is already created on the first run, thus succeeding run will definitely fail as describe on the earlier part of this document.

Sample Output

Below is the sample output when you run the above example.

java lang File createNewFile() example output

Contact Info

Singapore

Our Goal

JavaTutorialHQ aims to to be The Ultimate Guide on Java with hundreds of examples from basic to advance Topics.

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close