[英]java how to check if file exists and open it?
如何檢查文件是否存在並打開?
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對象,然后使用其exist()方法進行檢查。 然后可以將該文件對象傳遞到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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.