I need a valid method to check if a String represents a path for file or a directory. What are valid directory names in Android? As it comes out, folder names can contain '.' chars, so how does system understand whether there's a file or a folder?

推荐答案

Assuming path is your 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

See File Javadoc


Or you can use the NIO class Files and check things like this:

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

Java相关问答推荐

如何在Javascript中设置文本区域圆角的样式

H2弹簧靴试验跌落台

填写文本字段后锁定PDF

替换com. sun. jndi. dns. DnsContextFactory Wildfly23 JDK 17

SpringBoot+Java 17@Valid未验证POJO

基于调车场算法的科学计算器

如何正确创建序列图?

Helidon 4和Http API

Spring-Boot Kafka应用程序到GraalVM本机映像-找不到org.apache.kafka.streams.processor.internals.DefaultKafkaClientSupplier

在执行流和相关操作时,使用Java泛型为2个方法执行相同的操作,但对象不同

Java中不兼容的泛型类型

Java中HashSet的搜索时间与TreeSet的搜索时间

为什么这种递归会有这样的行为?

使IntelliJ在导入时优先 Select 一个类或将另一个标记为错误

在缺少字段时使用Jackson With Options生成Optional.Empty()

Android无法在Java代码中调用Kotlin代码,原因是在Companion中使用Kotlin枚举时

HBox内部的左对齐按钮(如果重要的话,在页码内)

谷歌应用引擎本地服务器赢得';t在eclipse上运行

Hibernate 命名策略导致 Java Spring Boot 应用程序中出现未知列错误

如何在 Android Studio 中删除 ImageView 和屏幕/父级边缘之间的额外空间?