-1

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!

cigien
  • 57,834
  • 11
  • 73
  • 112
Beepboop
  • 1
  • 1
  • Does this answer your question? [Check if file is in (sub)directory](https://stackoverflow.com/questions/18227634/check-if-file-is-in-subdirectory) – Kemal Abdic Sep 09 '22 at 09:04
  • Try to avoid the old cumbersome file api (`File`). It got replaced by NIO (`Files`, `Path`). Its easier to use, has better error messages and less irritating behavior. – Zabuzard Sep 09 '22 at 09:05
  • 4
    Please do not vandalize your posts. By posting on this site, you've irrevocably granted the Stack Exchange network the right to distribute that content under the [CC BY-SA 4.0 license](//creativecommons.org/licenses/by-sa/4.0/) for as long as it sees fit to do so. For alternatives to deletion, see: [I've thought better of my question; can I delete it?](https://stackoverflow.com/help/what-to-do-instead-of-deleting-question) – Spevacus Sep 09 '22 at 13:35

2 Answers2

2

You could use Files.walk()

Path folderPath = folder.toPath();
boolean containsFile = Files.walk(folderPath)
                              .anyMatch(p -> p.getFileName().toString().equals(fileName));
René Link
  • 48,224
  • 13
  • 108
  • 140
0

Use this

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

Naveen Roy
  • 85
  • 12