java

How to create a file in Java

In this tutorial, we are going to see how to create a file in Java. The File.createNewFile() method is used to create a file in Java and return a Boolean value: true if the file is created successfully; false if the file already exists or if the operation failed.
 

How to create a file in Java
import java.io.*;

public class Main 
{
    public static void main( String[] args )
    {	
    	try {
    		 
	      File myFile = new File("C:\\Users\\PC\\Desktop\\MyFile.txt"); 
	      
	      if (myFile.createNewFile()){
	        System.out.println("The file is created.");
	      }else{
	        System.out.println("File already exists.");
	      }
	      
    	} catch (IOException e) {
	      e.printStackTrace();
    	}
    }
}

Output:

The file is created.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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