How to create a file in Java

The createNewFile() method of the File class is used to create a new file in Java. The method creates an empty file at the location specified in the File object and returns true if the named file does not exist and was successfully created; false if the named file already exists

Syntax

Have a look below at the signature of the createNewfile() method:

svg viewer

Code

The code snippet below illustrates how the createNewFile() method is used to create a new file in Java:

import java.io.File;
import java.io.IOException;
class NewFileDemo {
public static void main( String args[] ) {
try
{
// The path argument passed to the File constructor
// is relative. It can also be like "C:\\Users\\Hassan\\Educative.txt"
File MyFile = new File("Educative.txt");
if (MyFile.createNewFile())
{
System.out.println("File created successfully!");
}
else
{
System.out.println("File already exists.");
}
// Any exception will be caught here
} catch (IOException e) {
System.out.println("An I/O error occurred.");
}
}
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved