【发布时间】:2012-09-28 15:04:42
【问题描述】:
我需要一个有效的方法来检查 String 是否代表文件或目录的路径。 Android 中的有效目录名称是什么?原来文件夹名可以包含'.'字符,那么系统如何判断是文件还是文件夹呢?
【问题讨论】:
-
“系统如何理解是否有文件或文件夹”:系统如何不理解?它在文件系统的磁盘上,是其中之一。
标签: java android file path directory
我需要一个有效的方法来检查 String 是否代表文件或目录的路径。 Android 中的有效目录名称是什么?原来文件夹名可以包含'.'字符,那么系统如何判断是文件还是文件夹呢?
【问题讨论】:
标签: java android file path directory
假设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
或者您可以使用 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
【讨论】:
path 在我的示例中是String。为什么不能创建File 实例?请注意,这不会改变文件系统上的任何内容。
root 可能是一个文件。文件不一定有 .something 扩展名。
使用 nio API 的清洁解决方案:
Files.isDirectory(path)
Files.isRegularFile(path)
【讨论】:
File 对象。节省内存
请坚持使用 nio API 来执行这些检查
import java.nio.file.*;
static Boolean isDir(Path path) {
if (path == null || !Files.exists(path)) return false;
else return Files.isDirectory(path);
}
【讨论】:
如果文件系统中不存在,系统无法告诉您String 是代表file 还是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
对于以下示例:
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
所以我们看到在这两种情况下系统都返回 false。 java.io.File 和 java.nio.file.Path 都是如此
【讨论】:
String path = "Your_Path";
File f = new File(path);
if (f.isDirectory()){
}else if(f.isFile()){
}
【讨论】:
要以编程方式检查字符串是否代表路径或文件,您应该使用 API 方法,例如 isFile(), isDirectory().
系统如何判断是文件还是文件夹?
我猜,文件和文件夹条目保存在一个数据结构中,由文件系统管理。
【讨论】:
public static boolean isDirectory(String path) {
return path !=null && new File(path).isDirectory();
}
直接回答问题。
【讨论】:
private static boolean isValidFolderPath(String path) {
File file = new File(path);
if (!file.exists()) {
return file.mkdirs();
}
return true;
}
【讨论】: