1

For example I have a path named ’logs/results.log’. the 'results.log' is a file. I want to know whether the directory in the file path exist. Note that the file path is a string.

Note: I want to check whether the directory contained in the given path is existed. For my example I want to check whether the 'logs/' is a directory but not whether the 'logs/results.log' is a directory. One of my confusion is about whether the directory is 'logs' or 'logs/'.

Rui
  • 117
  • 2
  • 12
  • Does this answer your question? [How to check if a folder exists](https://stackoverflow.com/questions/15571496/how-to-check-if-a-folder-exists) – ZhekaKozlov Jun 23 '20 at 05:08
  • No, what I want to asked is whether the directory contained in the path is exist. For example, I have file path ’logs/results.log’ and I want to know whether the ’logs/’ is a valid directory. The question given only check whether the given String is a path or directory if I understand it correctly. – Rui Jun 23 '20 at 05:15

3 Answers3

0
File file = new File("logs/results.log");

if (file.exists() && file.getParentFile() != null && file.getParentFile().isDirectory()) {
    System.out.println("Parent file is a directory.");
}
jaylordibe
  • 111
  • 4
0

Using Files.isDirectory:

private static boolean dirExists(String file) {
    Path parent = Paths.get(file).getParent();
    return parent != null && Files.isDirectory(parent);
}

Usage:

System.out.println(dirExists("logs/results.log"));
ZhekaKozlov
  • 36,558
  • 20
  • 126
  • 155
-1

Using java.nio.file.Files:

Path path = logs/result.log;

if (Files.exists(path)) {
// ...
}
BALAJI V S
  • 63
  • 6