java如何检查文件是否存在并打开它?
问题描述:
如何检查文件是否存在并打开它?
how to check if file exists and open it?
if(file is found)
{
FileInputStream file = new FileInputStream("file");
}
答
File.isFile
将告诉您文件存在且不是目录。
File.isFile
will tell you that a file exists and is not a directory.
请注意,您的检查和尝试之间的文件可能会被删除打开它,该方法不会检查当前用户是否具有读取权限。
Note, that the file could be deleted between your check and your attempt to open it, and that method does not check that the current user has read permissions.
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.
}
}