Sea*_*ney 1302
使用java.io.File
:
File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) {
// do something
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*ail 414
我建议使用isFile()
而不是exists()
.大多数情况下,您要检查路径是否指向文件,而不仅仅是它存在.请记住,exists()
如果路径指向目录,则返回true.
new File("path/to/file.txt").isFile();
Run Code Online (Sandbox Code Playgroud)
new File("C:/").exists()
将返回true但不允许您打开并作为文件读取它.
Won*_*nil 137
通过在Java SE 7中使用nio,
import java.nio.file.*;
Path path = Paths.get(filePathString);
if (Files.exists(path)) {
// file exist
}
if (Files.notExists(path)) {
// file is not exist
}
Run Code Online (Sandbox Code Playgroud)
如果两者都存在且notExists返回false,则无法验证文件是否存在.(也许没有访问权限)
您可以检查路径是目录还是常规文件.
if (Files.isDirectory(path)) {
// path is directory
}
if (Files.isRegularFile(path)) {
// path is regular file
}
Run Code Online (Sandbox Code Playgroud)
请查看此Java SE 7教程.
Wen*_*del 44
使用Java 8:
if(Files.exists(Paths.get(filePathString))) {
// do something
}
Run Code Online (Sandbox Code Playgroud)
小智 26
File f = new File(filePathString);
Run Code Online (Sandbox Code Playgroud)
这不会创建物理文件.将只创建类File的对象.要物理创建文件,您必须显式创建它:
f.createNewFile();
Run Code Online (Sandbox Code Playgroud)
因此f.exists()
可以用来检查这样的文件是否存在.
小智 25
f.isFile() && f.canRead()
Run Code Online (Sandbox Code Playgroud)
Rag*_*air 16
有多种方法可以实现这一目标.
只是为了存在.它可以是文件或目录.
new File("/path/to/file").exists();
Run Code Online (Sandbox Code Playgroud)检查文件
File f = new File("/path/to/file");
if(f.exists() && f.isFile()) {}
Run Code Online (Sandbox Code Playgroud)检查目录.
File f = new File("/path/to/file");
if(f.exists() && f.isDirectory()) {}
Run Code Online (Sandbox Code Playgroud)Java 7方式.
Path path = Paths.get("/path/to/file");
Files.exists(path) // Existence
Files.isDirectory(path) // is Directory
Files.isRegularFile(path) // Regular file
Files.isSymbolicLink(path) // Symbolic Link
Run Code Online (Sandbox Code Playgroud)jus*_*ody 14
在谷歌上首次点击"java file exists":
import java.io.*;
public class FileTest {
public static void main(String args[]) {
File f = new File(args[0]);
System.out.println(f + (f.exists()? " is found " : " is missing "));
}
}
Run Code Online (Sandbox Code Playgroud)
use*_*421 11
别.只需捕获FileNotFoundException.
文件系统必须测试文件是否仍然存在.完成所有这两次没有意义,有几个原因没有,例如:
不要试图猜测系统.它知道.并且不要试图预测未来.一般来说,测试任何资源是否可用的最佳方法就是尝试使用它.
小智 8
对我来说,Sean AO Harney接受的答案和Cort3z的评论结果似乎是最好的解决方案.
使用以下代码段:
File f = new File(filePathString);
if(f.exists() && f.isFile()) {
//do something ...
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助某人.
我知道我在这个线程中有点晚了。但是,这是我的答案,自 Java 7 及更高版本起有效。
以下片段
if(Files.isRegularFile(Paths.get(pathToFile))) {
// do something
}
Run Code Online (Sandbox Code Playgroud)
完全令人满意,因为如果文件不存在,方法isRegularFile
将返回false
。因此,无需检查是否Files.exists(...)
。
请注意,其他参数是指示应如何处理链接的选项。默认情况下,遵循符号链接。
熟悉 Commons FileUtils https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html 这也有额外的方法来管理文件和通常比JDK更好。
归档时间: |
|
查看次数: |
1106980 次 |
最近记录: |