gpt4 book ai didi

java - 在调用 openFileInput 之前检查文件是否存在

转载 作者:IT老高 更新时间:2023-10-28 20:24:30 24 4
gpt4 key购买 nike

要从应用程序的私有(private)存储区读取 Android 中的文件,请使用函数openFileInput()

我的问题是,有没有办法在调用这个函数之前检查这个文件是否存在?该函数可以抛出 FileNotFoundException,但我觉得调用它然后基于 try-catch 执行某些操作是一种不好的做法。

使用 File.exist() 似乎也很奇怪,因为它需要实例化一个类,我不确定是否只是将文件名传递给它会得到它在我手机的私密区域中找到该文件。

最佳答案

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

编辑:

此外,还有另一种方法可以将文件存储在外部存储中。

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

if(f.exists())
return;

关于java - 在调用 openFileInput 之前检查文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8867334/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com