如何避免 FileNotFoundException?如何检查Android中的文件是否为accessible/exists?

How to avoid FileNotFoundException? How to check if a file is accessible/exists in Android?

我对 java.io.FileNotFoundException 有疑问。有时我会得到这个例外,有时不会。不知道为什么,因为指定的文件存在。我认为该文件可能被另一个应用程序或系统使用。

我如何知道文件 exists/is 何时可供 reading/writing 访问?

谢谢。

错误日志:

IOKt 错误 java.io.FileNotFoundException:/storage/emulated/0/Android/data/com.android.vending/files/20170321_161318.txt:打开失败:ENOENT(没有这样的文件或目录)

查看 File.exists()。但是您的代码应该能够处理 FileNotFoundException。此外,您应该真正调查为什么首先得到它(也许异常消息会包含线索),因为它可能是由代码中的错误引起的。

FileNotFoundException 文档解释说:

This exception will be thrown by the {@link FileInputStream}, {@link FileOutputStream}, and {@link RandomAccessFile} constructors when a file with the specified pathname does not exist. It will also be thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.

所以你应该确保你有文件的权限,比如canRead(),canWrite()方法在java.io.File class.