How to Create New File in Java


In this example, let’s us see how to create a new file in Java.

Source Code

package com.beginner.examples;

import java.io.*;

public class FileOperator1Example { 
	public static void main(String[] args )
    {	
    	try
    	{ 
		      File file = new File("example.txt");
		      if (!file.exists())
		      { 
		    	  file.createNewFile();
		    	  System.out.println("The file is created.");
		      }
		      else
		      {
		    	  System.out.println("The file already exists.");
		      }
    	} 
    	catch (IOException e) 
    	{
    		e.printStackTrace();
    	}
    }
}

Output:

The file is created.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments