检查文件是否调用openFileInput之前存在 [英] Check if a file exists before calling openFileInput

查看:927
本文介绍了检查文件是否调用openFileInput之前存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要由你的应用程序使用的函数读取Android的文件私有存储区域 openFileInput

我的问题是,有没有办法来检查,如果该文件调用此函数之前存在?该功能可以通过FileNotFoundException异常,但我觉得调用这个,然后做基于一个尝试的缺点是不好的做法事。

使用File.exist似乎是一个奇怪的使用也因为它需要实例化一个类,我不知道,如果只是将文件传递到它的名字会得到它来查找该文件中的专用区域我手机。

解决方案

 公共布尔FILEEXISTS(上下文的背景下,字符串文件名){
    文件fil​​e = context.getFileStreamPath(文件名);
    如果(文件==空||!file.exists()){
        返回false;
    }
    返回true;
}
 

编辑:

此外,这里是另一种方式在外部存储器中的文件。

 字符串fileUrl =/appname/data.xml;
字符串文件= android.os.Environment.getExternalStorageDirectory()getPath()+ fileUrl。
文件F =新的文件(文件);

如果(f.exists())
返回;
 

To read a file in android from your apps private storage area you use the functionopenFileInput.

My question is, is there a way to check if this file exists before calling this function? The function can through a FileNotFoundException, but I feel like calling this and then doing something based on a try catch is bad practice.

Using File.exist seems like a strange thing to use also since it would require instantiating a class and I am not sure if just passing the name of the file to it would get it to find the file in the private area of my phone.

解决方案

public boolean fileExists(Context context, String filename) {    
    File file = context.getFileStreamPath(filename);
    if(file == null || !file.exists()) {
        return false;
    }
    return true;
}

EDIT:

Also, here is another way for files in external storage.

String fileUrl = "/appname/data.xml";
String file = android.os.Environment.getExternalStorageDirectory().getPath() + fileUrl;
File f = new File(file);

if(f.exists())
return;

这篇关于检查文件是否调用openFileInput之前存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆