Create New File In Java

In this little Java code example you will learn how to create a new file in Java. Please note that the path to the file is absolute. Also note the use of createNewFile() function which will also check for existence of the file before creating a new one. So there is no need to write additional code to check if file exists.

package com.appsdeveloperblog;

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

 
public class CreateNewFile {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {

            File file = new File("c:\\myfile.txt");
 
            if (file.createNewFile()) {
                System.out.println("A new File is created!");
            } else {
                System.out.println("This file already exists.");
            }

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

}

Leave a Reply

Your email address will not be published. Required fields are marked *