Create a new empty file in Java


A new empty file with the required abstract path name can be created using the method java.io.File.createNewFile(). This method requires no parameters and it returns true if the file is newly created and it did not exist previously. If the file existed previously, it returns false.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.io.File;
public class Demo {
   public static void main(String[] args) {
      try {
         File file = new File("demo1.txt");
         file.createNewFile();
         System.out.println("File: " + file);
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

The output of the above program is as follows −

Output

File: demo1.txt

Now let us understand the above program.

The file is created using the method java.io.File.createNewFile(). Then the file name is printed. A code snippet that demonstrates this is given as follows −

try {
   File file = new File("demo1.txt");
   file.createNewFile();
   System.out.println("File: " + file);
} catch(Exception e) {
   e.printStackTrace();
}

Updated on: 30-Jul-2019

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements