How to check if a file exists within a subdirectory of a directory in Java?

Viewed 73

This is my current code:

File f = new File(folder, fileName);
if (!f.exists()) {
    log.warn("Unable to find file");
} 
else{
    f.delete();
}

My problem is that this will always be true in the current context since I have two subfolders that have been generated and hashed. So let's assume I have a leading directory called "data storage" with two sub-directories with randomly hashed names. The file is within the two subdirectories. Is there an easy way to check if my file is within an entire directory, including sub-directories?

Thanks!

2 Answers

You could use Files.walk()

Path folderPath = folder.toPath();
boolean containsFile = Files.walk(folderPath)
                              .anyMatch(p -> p.getFileName().toString().equals(fileName));

Use this

File f = new File("yourfilepath/filename.ext");
if(f.exists()){
    System.out.println("success");
}
else{
    System.out.println("fail");
}

Related