Java Create New Empty File

Learn how to create a new empty file in java. We will use the File class createNewFile() method to achieve this task.

According to Java docs,

createNewFile() method returns a boolean value. It returns true if and only if the named file (javahungry.txt) does not exist and was successfully created.
It returns false if the named file (javahungry.txt) already exists.

Read Also: How to Create a File in Java

I will be sharing two examples of creating a new empty file using createNewFile() method

1. No pathname is given for the file
2. With valid pathname given for the file  

1. No pathname

Since the pathname is unspecified, below code will create the new empty file in the current location.


import java.io.*;

public class JavaHungry {
public static void main(String args[]) {

try
{
// File object is created
File file = new File("javahungry.txt");

/* If named file does not exist and was
successfully created, then createNewFile() method
will return true, otherwise false*/
boolean isFileCreated = file.createNewFile();

/* isFileCreated is true if you run the
program for the first time, but if you run the
program for second time then it will return false
because file already exists */
System.out.println("Is "+ file.getName()+ " created : "+ isFileCreated);

// Displaying the length of the file
System.out.println(file.getName()+ " is empty and length : "+ file.length());
}

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

Output:
Is javahungry.txt created : true
javahungry.txt is empty and length : 0


2. With Valid pathname

Provide a valid pathname while creating the File object. Given below are the examples of Windows OS and Mac OS.


import java.io.*;

public class JavaHungry {
public static void main(String args[]) {

try
{
// File object with valid path for Windows OS
File file = new File("C://javahungry.txt");

// File object with valid path for Mac OS
// File file = new File("/Users/SubhamMittal/Desktop/javahungry.txt");

boolean isFileCreated = file.createNewFile();
System.out.println("Is "+ file.getName()+ " created: "+ isFileCreated);
}

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

Output:
Is javahungry.txt created : true

That's all for today. Please mention in comments in case you have any questions related to create a new empty file in java.

0 Comments