2011-10-08 100 views

回答

51

这应该做的伎俩,我把它换成硬编码的SD卡参考推荐的API调用getExternalCacheDir()

File file = new File(getExternalCacheDir(), "mytextfile.txt"); 
if (file.exists()) { 
    //Do action 
} 
+0

非常感谢你 – androiddevs78

+4

请注意存在与否:getExternalCacheDir ()可能不是你想要的。如果您想要在sd上安装一个目录,在卸载应用程序后(例如“缓存”目录),请使用getExternalCacheDir()。但是,如果你想要SD卡的顶级目录,那么你可能会更好地使用:File sdDir = new File(Environment.getExternalStorageDirectory()。getPath()); – DEzra

0

您必须创建一个文件,并将其设置为必需的文件,并检查它是否存在。

String FILENAME="mytextfile.txt"; 
File fileToCheck = new File(getExternalCacheDirectory(), FILENAME); 
if (fileToCheck.exists()) { 
FileOutputStream fos = openFileOutput("sdcard/mytextfile.txt", MODE_WORLD_WRITEABLE); 
} 

玩得开心!

+0

最好不要使用SD卡的硬编码参考,请参阅我以前的答案,以获得访问外部存储的更好方法。 – Ljdawson

0

如果指定的文件不存在,构造函数FileOutputStream将抛出FileNotFound异常。有关更多信息,请参阅Oracle documentation

此外,请确保您有权限access the SD card

0

检查是否与布尔类型的条件一样

File file = new File(path+filename); 
if (file.exists() == true) 
{ 
//Do something 
} 
+0

上面的代码中'== true'是redondant。你可以用'if(file.exists())'代替。 – Slander

2

* 使用此您可以检查该文件是在SD卡*

File file = new File(sdcardpath+ "/" + filename); 
if (file.exists()) 
{ 

}