Java File createNewFile() method with examples

November 28, 2019 No comments Java IO Examples createNewFile

1. Introduction

The createNewFile() method creates a new and empty file with specified name. This operation succeeded when the name does not yet exist. Checking for the existence of the file and creation of the file are atomic operations. Note that this method should not be used for file-locking.

2. Method signature

public boolean createNewFile() throws IOException

Parameters:

  • method does not take any parameter

Returns

  • true - if the file does not exists already and was created successfully

Throws

  • IOException - if any of I/O error occurred
  • SecurityException - when we do not have access to the file

3. Examples

3.1. Create a new file in the /tmp directory

package com.frontbackend.java.io.examples;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File f = new File("/tmp/frontbackend.txt");
            boolean status = f.createNewFile();

            if (status) {
                System.out.println("File successfully created");
            } else {
                System.out.println("File was not created");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output:

File successfully created

In case the file already exists, method f.createNewFile() will return false and we will get the following result:

The file was not created

3.2. Create a new file and check common parameters

package com.frontbackend.java.io.examples;

import java.io.File;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File f = new File("/tmp/frontbackend.txt");
            boolean status = f.createNewFile();

            if (status) {
                System.out.println("Exists: " + f.exists());
                System.out.println("Path: " + f.getPath());
                System.out.println("Can write: " + f.canWrite());
                System.out.println("Can read: " + f.canRead());
                System.out.println("Is directory: " + f.isDirectory());
                System.out.println("Is hidden: " + f.isHidden());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output:

Exists: true
Path: /tmp/frontbackend.txt
Can write: true
Can read: true
Is directory: false
Is hidden: false

4. Conclusion

In this article we presented File.createNewFile() a method that can be used to create a new file in an atomic way. Method checks if a file with a given name already exists before creating a new file, and this a single operation with respect to all other filesystem activities that might affect the file.

{{ message }}

{{ 'Comments are closed.' | trans }}