file.exists()返回现有文件的false(对于与PDF不同的任何内容)



sdcard上都存在两个文件,但是无论出于何种原因, exists()返回png文件的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 exists");
    } else {
        LOG.x("file does not exist");
    }
}

现在,我已经看了引擎盖下的内容以及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;
    }
}

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

如果是这样,

  • 我该如何使这项工作?
  • 其他哪些选项可以检查是否可以使用SDCARD上的文件?

谢谢。

1您需要获得设备的许可

将其添加到AndroidManifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

2获取外部存储目录

File sdDir = Environment.getExternalStorageDirectory();

3终于检查文件

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

注意:文件名是sdcard的路径,而不是root。

例如:您想要查找

/mnt/sdcard/Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png

然后文件名是

./Android/data/com.gemoro.toffer/cache/1551619351/0/foto/-921042926.png

请尝试此代码。希望它对您有帮助。我只使用此代码。它对我来说正常发现该文件是否存在。请尝试让我知道。

File file = new File(path);
    if (!file.isFile()) {
         Log.e("uploadFile", "Source File not exist :" + filePath);
    }else{
    Log.e("uploadFile","file exist");
}

检查USB存储是否未连接到PC。由于Android设备已连接到PC,因为存储该文件无法用于应用程序,并且您会false file.exists()。

在内部存储中存在检查文件

示例:/storage/emulation/0/folder_name/file_name.extention

  1. 检查许可(写存储)

  2. 并且检查文件是否存在

    public static boolean isFilePresent(String fileName) { return getFilePath(fileName).isFile(); }

  3. 从文件名获取文件

    public static File getFilePath(String fileName){ String extStorageDirectory = Environment.getExternalStorageDirectory().toString(); File folder = new File(extStorageDirectory, "FOLDER_NAME"); File filePath = new File(folder + "/" + fileName); return filePath; }

相关内容

最新更新