尝试检查内部存储中是否存在文件

use*_*645 33 java android

以下代码是我试图识别内部存储中是否存在文件的方法MODE_PRIVATE.

public boolean isset(String filename){
    FileInputStream fos = null;
    try {
       fos = openFileInput(filename);
       //fos = openFileInput(getFilesDir()+"/"+filename);
       if (fos != null) {
         return true;
       }else{
         return false;
       }
    } catch (FileNotFoundException e) {
        return false;
    }

    //File file=new File(mContext.getFilesDir(),filename);

    //boolean exists = fos.exists();
    }
Run Code Online (Sandbox Code Playgroud)

但是,它进入异常并且不继续使用代码.它没有回报.为什么?

Has*_*y31 114

希望这种方法可以帮到你.

public boolean fileExist(String fname){
    File file = getBaseContext().getFileStreamPath(fname);
    return file.exists();
}
Run Code Online (Sandbox Code Playgroud)

  • 正确答案,Michael Petrotta你应该接受这个 (3认同)
  • @bsara 为什么使用基本上下文而不是应用程序上下文,或者两者都有效? (2认同)

Nis*_*nth 9

对于内部存储,这对我有用:

public boolean isFilePresent(String fileName) {
    String path = getContext().getFilesDir().getAbsolutePath() + "/" + fileName;
    File file = new File(path);
    return file.exists();
}
Run Code Online (Sandbox Code Playgroud)