Create a New Empty File in Java

You are currently viewing Create a New Empty File in Java

Create a new empty file in Java

//Java code to create a new empty file


public class Main {
  public static void main(String[] args) {
    //creating file object
    File file = new File("sample.txt");

    //following syntax can be used to define 
    //path (D://sample.txt) also
    //File file = new File("D://sample.txt");

    //variable to store result
    //'true' - file created successfully
    //'false' - file is not created successfully
    boolean result = false;

    try {
      result = file.createNewFile();
      System.out.println(file.getPath() + " created successfully...");
    } catch (IOException exp) {
      System.out.println("Error while creating file: " + exp);


sample.txt created successfully...


Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply