Java create file



Live Example :

package com.c4learn.file;

import java.io.File;
import java.io.IOException;

public class CreateFile {

    public static void main(String[] args) {
     try {

          File file = new File("c:PriteshsampleFile.txt");

          if (file.createNewFile()){
              System.out.println("File created Successfully !!");
          }else{
              System.out.println("File already exists.");
          }

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

}

Output :

File created Successfully !!

Explanation :

  1. File.createNewFile() method is used to create new file.
  2. Above method will return Boolean value i.e True or False
  3. Package to be Imported :
    java.io.IOException