Create File in Java

 Posted On  | Yashwant Chavan 

In this tutorial we will learn how to create a new file in Java. java.io.File.createNewFile() Creates a new empty file named by this abstract pathname. If and only if a file with this name does not yet exist.

File.createNewFile() syntax

java.io.File.createNewFile() Creates a new empty file named by this abstract pathname. If and only if a file with this name does not yet exist.

boolean java.io.File.createNewFile() throws IOException

Returns - true if the named file does not exist and was successfully created; false if the named file already exists

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 named file

Create new file example

Below example shows how to create new file using java.io.File.createNewFile() method.

package com.technicalkeeda.app;

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

public class CreateFileExample {
    public static void main(String[] args) {
        try {
            File file = new File("c:\\demo.txt");
            file.createNewFile();
            System.out.println(file.getPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output

c:\demo.txt


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0311 seconds.