java如何检查文件是否存在并打开它?

如何检查文件是否存在并打开它?

if(file is found) { FileInputStream file = new FileInputStream("file"); } 

File.isFile会告诉您文件存在且不是目录。

请注意,可以在检查和尝试打开文件之间删除该文件,并且该方法不会检查当前用户是否具有读取权限。

 File f = new File("file"); if (f.isFile() && f.canRead()) { try { // Open the stream. FileInputStream in = new FileInputStream(f); // To read chars from it, use new InputStreamReader // and specify the encoding. try { // Do something with in. } finally { in.close(); } } catch (IOException ex) { // Appropriate error handling here. } } 

您需要先创建一个File对象,然后使用其exists()方法进行检查。 然后可以将该文件对象传递给FileInputStream构造函数。

 File file = new File("file"); if (file.exists()) { FileInputStream fileInputStream = new FileInputStream(file); } 

使用File#exists 。

您可以在文档中找到exists方法:

 File file = new File(yourPath); if(file.exists()) FileInputStream file = new FileInputStream(file);