如何检查文件是否存在并打开它?
if(file is found)
{
FileInputStream file = new FileInputStream("file");
}
Run Code Online (Sandbox Code Playgroud)
Mik*_*uel 15
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.
}
}
Run Code Online (Sandbox Code Playgroud)
您需要先创建一个File对象,然后使用其exists()方法进行检查.然后可以将该文件对象传递给FileInputStream构造函数.
File file = new File("file");
if (file.exists()) {
FileInputStream fileInputStream = new FileInputStream(file);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
31013 次 |
| 最近记录: |