In this tutorial, we will see how to check if an expected folder (directory) exists or not using the JAVA code. In order to do so, first we would need to create a temporary folder first and then we will perform the existence check.
Simple example to test if Folder present or not in Java, Share It... Share on X
Let’s say:
If any temporary folder present at this path ‘C:\\Users\\isha’, then below code will through true else it will throw false. Lets examine that in the below code:
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 33 34 35 36 37 38 39 40 41 | import java.io.File; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; public class VerifyFolderExists { public static void main(String[] args) throws IOException { Path rootDirectory = FileSystems.getDefault().getPath("C:\\Users\\isha"); Path tempDirectory = Files.createTempDirectory(rootDirectory, ""); System.out.println(tempDirectory); //should throw true as folder present System.out.println("Folder present : " + checkIfFolderExists(tempDirectory.toString())); //delete the folder tempDirectory.toFile().delete(); //should throw false as folder has been deleted System.out.println("Folder present : " + checkIfFolderExists(tempDirectory.toString())); } public static boolean checkIfFolderExists(String folderName) { boolean found = false; try { File file = new File(folderName); if (file.exists() && file.isDirectory()) { found = true; } } catch (Exception e) { e.printStackTrace(); } return found; } } |
1. Creating the temp folder:
As mentioned at the top, first we need to create a temporary folder using below code.
1 2 | Path rootDirectory = FileSystems.getDefault().getPath("C:\\Users\\isha"); Path tempDirectory = Files.createTempDirectory(rootDirectory, ""); |
2. Usage of ‘exists’ method:
Once the folder has been created, we are going to use ‘exists‘ and ‘isDirectory’ method of Java-IO library. They will test whether the folder is present or not and if it’s a directory or not, based on the output, it will throw ‘pass‘ or ‘fail‘ in return.
1 | file.exists() && file.isDirectory() |
3. Additional check after deleting the folder:
Now, by using below line of code, we are deleting the created folder and performing the folder existence check again.
1 2 | tempDirectory.toFile().delete(); System.out.println("Folder present : " + checkIfFolderExists(tempDirectory.toString())); |
Lets run the above specified ‘VerifyFolderExists’ class.
Eclipse Console Output:
1 2 3 | C:\Users\isha\1263434162168152523 Folder present : true Folder present : false |
That’s it, it’s that simple to check if File exists in Java :)
Simple example to test if Folder present or not in Java, Share It... Share on X
If you like this post , please check out my other useful blog posts:
Other Useful References: