检查路径是表示文件还是文件夹

Ego*_*gor 128 java directory android file path

我需要一个有效的方法来检查a是否String代表文件或目录的路径.Android中有效的目录名称是什么?当它出来时,文件夹名称可以包含'.'字符,那么系统如何理解是存在文件还是文件夹?提前致谢.

Baz*_*Baz 185

假设path是你的String.

File file = new File(path);

boolean exists =      file.exists();      // Check if the file exists
boolean isDirectory = file.isDirectory(); // Check if it's a directory
boolean isFile =      file.isFile();      // Check if it's a regular file
Run Code Online (Sandbox Code Playgroud)

FileJavadoc


或者您可以使用NIO类Files并检查以下内容:

Path file = new File(path).toPath();

boolean exists =      Files.exists(file);        // Check if the file exists
boolean isDirectory = Files.isDirectory(file);   // Check if it's a directory
boolean isFile =      Files.isRegularFile(file); // Check if it's a regular file
Run Code Online (Sandbox Code Playgroud)

  • isDirectory()方法仅在文件存在且它是目录时才返回true.如果路径中给出的文件不存在,那么它也返回false.因此,如果给定的路径不存在或者它存在但是它不是目录,则isDirectory()将返回false ...希望有帮助.. (8认同)

pgs*_*rom 47

使用nio API保持清洁解决方案:

Files.isDirectory(path)
Files.isRegularFile(path)
Run Code Online (Sandbox Code Playgroud)

  • 不回答所问的问题。* Files.isDirectory()*不接受字符串。 (2认同)
  • 从“字符串”开始?没问题... `Path path = Paths.get(myString);` 然后您就可以开始了! (2认同)

She*_*eng 20

请坚持使用nio API来执行这些检查

import java.nio.file.*;

static Boolean isDir(Path path) {
  if (path == null || !Files.exists(path)) return false;
  else return Files.isDirectory(path);
}
Run Code Online (Sandbox Code Playgroud)

  • @Baz因为Scala与Java协变......只是开玩笑:-D.我已经更新了答案. (6认同)
  • 当问题是要求Java代码(参见标签)时,为什么要在Scala中给出答案? (2认同)

Emd*_*won 9

如果文件系统中不存在,系统无法告诉您 a 是否String代表 afile或。例如:directory

Path path = Paths.get("/some/path/to/dir");
System.out.println(Files.isDirectory(path)); // return false
System.out.println(Files.isRegularFile(path)); // return false
Run Code Online (Sandbox Code Playgroud)

对于以下示例:

Path path = Paths.get("/some/path/to/dir/file.txt");
System.out.println(Files.isDirectory(path));  //return false
System.out.println(Files.isRegularFile(path));  // return false
Run Code Online (Sandbox Code Playgroud)

所以我们看到在这两种情况下系统都返回 false。这对于两者都是java.io.File如此java.nio.file.Path