Java-Create New File

Create New File

The createNewFile( ) method is creates a new empty file, returning true on success and false on failure. Failure indicates that the path specified in the File object already exists. Note this method is enclosed in a try block and followed by a catch block. This is necessary because the createNewFile( ) method throws an IO exception, if that the file cannot be created because the entire path does not exist yet. If we fail to catch the exception, program will not compile.

Program

Program Source

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

public class Javaapp {

    public static void main(String[] args) {
        
        File f1 = new File("C:\\java\\hajsof.txt");
        
        try{
            if(f1.createNewFile())
            {
                System.out.println("File Creation : Success");
            }else
            {
                System.out.println("File Creation : Unsuccess");
            }
        }catch (IOException io){}
    }
}

Leave a Comment