java tutorial - How to create a file in Java - java programming - learn java - java basics - java for beginners



 How to create a file in Java

Learn java - java tutorial - How to create a file in Java - java examples - java programs

  • File.createNewFile() It is used to create a new empty file atomatically and this name is abstract pathname and then if a file with this name does not exist.
  • File.createNewFile() Method returns true if the named file does not exist and it creates successfully; if the named file is already exists it returns false.

sample code:

import java.io.File;
import java.io.IOException;
 
public class Kaashiv_infotech
{
    public static void main( String[] args )
    {	
    	try {
    		 
	      File myfile = new File("C:\\Kaashiv_file.txt");
	      
	      if (myfile.createNewFile())
	      {
	        System.out.println("New File is created!");
	      }
	      else
	      {
	        System.out.println("File with the same name already exists.");
	      }
	      
    	} 
    	catch (IOException e)
    	{
	      e.printStackTrace();
	    }
    }
}

Output:

New File is created!

Related Searches to How to create a file in Java