如何检查文件是否存在于 Java 中? [英] How do I check if a file exists in Java?

查看:35
本文介绍了如何检查文件是否存在于 Java 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在打开文件以在 Java 中读取之前检查文件是否存在(相当于 Perl 的 -e $filename)?

How can I check whether a file exists, before opening it for reading in Java (the equivalent of Perl's -e $filename)?

唯一的关于SO的类似问题涉及编写文件,因此使用FileWriter 显然在这里不适用.

The only similar question on SO deals with writing the file and was thus answered using FileWriter which is obviously not applicable here.

如果可能的话,我更喜欢真正的 API 调用返回真/假,而不是一些调用 API 来打开文件并在它抛出异常时进行捕获并检查无文件"在文本中",但我可以接受后者.

If possible I'd prefer a real API call returning true/false as opposed to some "Call API to open a file and catch when it throws an exception which you check for 'no file' in the text", but I can live with the latter.

推荐答案

使用 java.io.File:

File f = new File(filePathString);
if(f.exists() && !f.isDirectory()) { 
    // do something
}

这篇关于如何检查文件是否存在于 Java 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆