android - file.exists()为现有文件返回false(对于不同于pdf的任何内容)

Gor*_*ail 12 android file

这两个文件都存在于SD卡上,但无论出于何种原因,exists()都会返回false文件.

//String path = "/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png";
  String path = "/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-1200240592.pdf";

File file2 = new File(path);

if (null != file2)
{
    if(file2.exists())
    {
        LOG.x("file exist");
    }
    else
    {
        LOG.x("file does not exist");
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我看看底层是什么,file.exists()实际上做了什么,这就是它的作用:

public boolean exists()
{
    return doAccess(F_OK);
}

private boolean doAccess(int mode)
{
    try
    {
        return Libcore.os.access(path, mode);
    }
    catch (ErrnoException errnoException)
    {
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

可能是通过抛出异常并返回false来完成该方法?

如果是这样,

  • 我怎样才能做到这一点
  • 还有哪些其他选项可以检查sdcard上是否存在文件?

谢谢.

Ale*_*Chi 14

1您需要获得设备的许可

将其添加到AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Run Code Online (Sandbox Code Playgroud)

2获取外部存储目录

File sdDir = Environment.getExternalStorageDirectory();
Run Code Online (Sandbox Code Playgroud)

3最后,检查文件

File file = new File(sdDir + filename /* what you want to load in SD card */);
if (!file.canRead()) {
    return false;
}
return true;
Run Code Online (Sandbox Code Playgroud)

注意:filename是sdcard中的路径,而不是root中的路径.

例如:你想找到

/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png
Run Code Online (Sandbox Code Playgroud)

然后文件名是

./Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png
Run Code Online (Sandbox Code Playgroud)

.