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)
或者您可以使用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)
pgs*_*rom 47
使用nio API保持清洁解决方案:
Files.isDirectory(path)
Files.isRegularFile(path)
Run Code Online (Sandbox Code Playgroud)
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)
如果文件系统中不存在,系统无法告诉您 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