【问题标题】:Trying to check if a file exists in internal storage尝试检查内部存储中是否存在文件
【发布时间】:2012-05-14 02:34:12
【问题描述】:

以下代码是我尝试识别内部存储中是否存在文件的方法,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();
    }

但是,它会进入异常并且不会继续执行代码。它不做回报。为什么?

【问题讨论】:

  • 你能提供给我们堆栈跟踪吗?

标签: java android


【解决方案1】:

希望这个方法对你有帮助。

public boolean fileExist(String fname){
    File file = getBaseContext().getFileStreamPath(fname);
    return file.exists();
}

【讨论】:

  • @bsara 为什么使用基本上下文而不是应用程序的上下文,或者两者都有效?
  • 您不需要任何上下文 - 如果您想从活动或服务访问文件,您可以直接进行。
【解决方案2】:

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

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

【讨论】:

  • 晚了一天,做空了美元,但如果你想缩短这个时间,getAbsolutePath() 不需要,因为getFilesDir() 已经返回了绝对路径。查看谷歌的文档here
【解决方案3】:

Kotlin:这对我有用!!

fun check(path: String?): Boolean
{
    val file = File(path)
    return file.exists()
}

【讨论】:

    猜你喜欢
    • 2018-07-11
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-12
    相关资源
    最近更新 更多