In this tutorial, we will write a program to check whether a new file is created or already exists in java. This java program check if the file is already created in that particular directory or it is already present.
The program also uses try and catch for exception handling. If you want to learn about Java files and Exceptions, click the link below.
Java Program to Check Whether a New file is Created or Already Exists
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | //check whether new file is created or already exists import java.io.*; public class FileCreated { public static void main(String[] args) { try { File file = new File("javaCode.txt"); if (file.createNewFile()) { System.out.println("New File is created."); } else { System.out.println("File already exists."); } } catch (IOException e) { e.printStackTrace(); } } } |
Output:
New File is created.
A new file will be created in the same directory.