Write a java program to Create a new file


This Java program demonstrates how to create a new file using the File class. The code creates an instance of the File class with the file name "file.txt". It then calls the createNewFile() method on this object, which tries to create a new file with the specified name.

The try block checks if the file creation was successful by calling the createNewFile() method. If the file is created successfully, the program prints the message "File Created Successfully.....". Otherwise, it prints the message "File Creation Failed....".

If an exception is thrown during the execution of the try block, the catch block will catch the exception and print the error message.

Overall, this program demonstrates how to create a new file using the File class in Java, and how to handle exceptions that may occur during the file creation process.

Source Code

import java.io.File;
public class Create_NewFile
{
	public static void main(String args[])
	{
		final String file_name = "file.txt";
 
		try{
			File obj = new File(file_name);
			if (obj.createNewFile())
			{
				System.out.println("File Created Successfully.....");
			}
			else
			{
				System.out.println("File Creation Failed....");
			}
		}
		catch (Exception Ex) {
			System.out.println("Exception : " + Ex.toString());
		}
	}
}

Output

File Creation Failed....