问题
我需要一个有效的方法来检查aString
是否代表文件或目录的路径。 Android中有效的目录名称是什么?当它出来时,文件夹名称可以包含'.'
chars,那么系统如何理解是存在文件还是文件夹?提前致谢。
#1 热门回答(142 赞)
假设2774177715是你的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
SeeFile
Javadoc
或者你可以使用NIO classFiles
并检查以下内容:
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
#2 热门回答(33 赞)
使用nio API时清洁解决方案:
Files.isDirectory(path)
Files.isRegularFile(path)
#3 热门回答(19 赞)
请坚持使用nio API来执行这些检查
import java.nio.file.*;
static Boolean isDir(Path path) {
if (path == null || !Files.exists(path)) return false;
else return Files.isDirectory(path);
}