In this tutorial, we will see how to check if an expected file exists or not using the JAVA code. We are going to use ‘File.exists()’ method of Java-IO library. In order to do so, first we would need to create a temporary file and then we will perform the existence check.
Simple example to test if File present or not in Java, Share It... Click To TweetExample:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import java.io.File; import java.io.IOException; public class CheckIfFileExists { static File tempFile; public static void main(String[] args) { //Lets create a temp file first try { tempFile = File.createTempFile("tempFile", ".txt"); } catch (IOException e) { e.printStackTrace(); } //Check if file exists System.out.println("File present : "+ tempFile.exists()); //And, now lets delete the file. tempFile.delete(); //Check if file exists System.out.println("File present : "+ tempFile.exists()); } } |
Let’s try to understand the code:
1. Creating the temp file:
As mentioned at the top, first we need to create a temporary file using below code.
1 2 3 | File tempFile; tempFile = File.createTempFile("tempFile", ".txt"); |
2. Usage of ‘exists’ method:
Once the file has been created, we are going to use ‘exists‘ method of Java-IO library. It will test whether the file is present or not and based on the output, it will throw ‘pass‘ or ‘fail‘ in return.
1 | tempFile.exists() |
3. Additional check after deleting the file:
Now, by using below line of code, we are deleting the created file and performing the file existence check again.
1 2 3 | tempFile.delete(); System.out.println("File present : "+ tempFile.exists()); |
Lets run the above specified ‘CheckIfFileExists’ class.
Eclipse Console Output:
1 2 | File present : true File present : false |
That’s it, it’s that simple to check if File exists in Java 🙂
Simple example to test if File present or not in Java, Share It... Click To Tweet
If you like this post , please check out my other useful blog posts:
Other Useful References: