Java create new file

Let’s learn how do you create a new file in java?

Java create new file

In this post we are going to learn to create a new file using createNewFile() method of File class which creates a new, empty file and returns a boolean value.

java create new file

In creating a new file, first create File object then call createNewFile() method to create new file.

createNewFile() method of File class returns true if the named file does not exist and was successfully created; false if the named file already exists.

If createNewFile() method is not able to create new file then IOException is thrown. Let’s see an example on createNewFile() method of File class.

import java.io.File;
import java.io.IOException;
public class CreateFileDemo
{
   public static void main(String[] args) throws IOException
   {
      try
      {
         File file = new File("D:\\demo.txt");
         boolean bool = file.createNewFile();
         if(bool)
         {
            System.out.println("File created successfully");
         }
         else
         {
            System.out.println("File already exists");
         }
      }
      catch(IOException ex)
      {
         System.out.println("Exception : ");
         ex.printStackTrace();
      }
   }
}

Output:

File created successfully


Also read – preface to java virtual machine and architecture