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

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

问题描述

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

处理写入文件,因此使用FileWriter来回答,这显然不适用于此。



如果可能的话,我宁愿一个真正的API调用返回true / false到一些调用API来打开一个文件,并抓住它时,它会引发一个异常,你检查文本中没有文件,但我可以住在后者。

java.io.File :

  File f = new File(filePathString); 
if(f.exists()&&!f.isDirectory()){
//做某事
}


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

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

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 text", but I can live with the latter.

解决方案

Using java.io.File:

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

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

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