我想检查SD卡上是否存在文本文件。文件名是mytextfile.txt。以下是代码:检查Android上的SD卡上是否存在文件
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
如何检查此文件是否存在?
我想检查SD卡上是否存在文本文件。文件名是mytextfile.txt。以下是代码:检查Android上的SD卡上是否存在文件
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
如何检查此文件是否存在?
这应该做的伎俩,我把它换成硬编码的SD卡参考推荐的API调用getExternalCacheDir():
File file = new File(getExternalCacheDir(), "mytextfile.txt");
if (file.exists()) {
//Do action
}
您必须创建一个文件,并将其设置为必需的文件,并检查它是否存在。
String FILENAME="mytextfile.txt";
File fileToCheck = new File(getExternalCacheDirectory(), FILENAME);
if (fileToCheck.exists()) {
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE);
}
玩得开心!
最好不要使用SD卡的硬编码参考,请参阅我以前的答案,以获得访问外部存储的更好方法。 – Ljdawson
如果指定的文件不存在,构造函数FileOutputStream
将抛出FileNotFound
异常。有关更多信息,请参阅Oracle documentation。
此外,请确保您有权限access the SD card。
检查是否与布尔类型的条件一样
File file = new File(path+filename);
if (file.exists() == true)
{
//Do something
}
上面的代码中'== true'是redondant。你可以用'if(file.exists())'代替。 – Slander
* 使用此您可以检查该文件是在SD卡*
File file = new File(sdcardpath+ "/" + filename);
if (file.exists())
{
}
非常感谢你 – androiddevs78
请注意存在与否:getExternalCacheDir ()可能不是你想要的。如果您想要在sd上安装一个目录,在卸载应用程序后(例如“缓存”目录),请使用getExternalCacheDir()。但是,如果你想要SD卡的顶级目录,那么你可能会更好地使用:File sdDir = new File(Environment.getExternalStorageDirectory()。getPath()); – DEzra