如何检查SD卡目录中是否存在文件

7

我想检查在安卓SD卡中是否存在给定的文件。我尝试使用绝对路径创建一个文件,并使用file.exists()进行检查,但是它没有起作用。文件的URL为"file:///mnt/sdcard/book1/page2.html",并且该文件确实存在。但是,一些原因导致file.exists()未显示相同的结果。


可能是在Android上检查SD卡中的文件是否存在的重复问题。 - Adriana Hernández
7个回答

51
File extStore = Environment.getExternalStorageDirectory();
File myFile = new File(extStore.getAbsolutePath() + "/book1/page2.html");

if(myFile.exists()){
    ...
}

这应该可以工作。


7
尝试像这样:

尝试像这样:

File file = new File(Environment.getExternalStorageDirectory() + "/book1/page2.html");
if (file.exists()) {
    /*...*/
}

同时确保您已经具备以下条件:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

在您的清单文件中。

1
您可以按照以下步骤进行检查:
  File file = new File(getExternalCacheDirectory(), "mytextfile.txt" );
  if (file.exists()) {
      //Do action
   }

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

已检查,这将正常工作


0
String filepath = getFilesDir().getAbsolutePath(); 
String FileName = "Yourfilename" ;
File FileMain = new File(filepath, FileName); 
if (FileMain.exists()){ 
do somthing here                     
}else{}

0
File logFile = new File(
        android.os.Environment.getExternalStorageDirectory()
                + "/book1/", "page2.tml");
if (logFile.exists())
    System.out.println("file exists");
else
    System.out.println("file does not exist

0
做类似这样的事情:
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "your/file/path");

if(yourFile.exists())
{

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接