如何检查文件是否存在并打开它?
if(file is found)
{
FileInputStream file = new FileInputStream("file");
}
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.
}
}
in
不会有任何损失。此外,in
变量不能在IOException
处理程序之外初始化,因为FileInputStream
构造函数会抛出IOException
处理程序,所以如果我将finally
移到外面,我就必须做一些愚蠢的技巧,比如将in
初始化为null并在finally
中检查它,这只会使事情更加复杂,即使我确实想忍受那种不必要的复杂性,我也需要在整个过程中使用try
,因为in.close()
可能会抛出一个IOException
。 - Mike Samuelin
。但是,in.close()
的传播异常可能会覆盖 in
的另一个方法也抛出异常时的异常。 - Charles Wu您需要先创建一个文件对象,然后使用它的exists()方法进行检查。该文件对象可以传递到FileInputStream构造函数中。
File file = new File("file");
if (file.exists()) {
FileInputStream fileInputStream = new FileInputStream(file);
}
您可以在文档中找到exists
方法:
File file = new File(yourPath);
if(file.exists())
FileInputStream file = new FileInputStream(file);