【问题标题】:How to check if a file exists in a directory in sd card如何检查sd卡目录中是否存在文件
【发布时间】:2012-07-02 18:57:19
【问题描述】:

我想检查给定的文件是否存在于 android sd 卡中。我正在尝试使用绝对路径创建文件并使用file.exists() 检查,但它不起作用。该文件的 URL 是 "file:///mnt/sdcard/book1/page2.html" 并且该文件确实存在。但不知何故,file.exists() 的显示不一样。

【问题讨论】:

标签: android file android-sdcard


【解决方案1】:

试试这样:

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

还要确保你有:

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

在您的清单文件中。

【讨论】:

    【解决方案2】:
    File file = new File(path+filename);
    if (file.exists())
    {
    //Do something
    }
    

    检查,这将工作

    【讨论】:

      【解决方案3】:

      您可以检查如下:

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

      【讨论】:

        【解决方案4】:
        String filepath = getFilesDir().getAbsolutePath(); 
        String FileName = "Yourfilename" ;
        File FileMain = new File(filepath, FileName); 
        if (FileMain.exists()){ 
        do somthing here                     
        }else{}
        

        【讨论】:

          【解决方案5】:

          做这样的事情:

          File dir = Environment.getExternalStorageDirectory();
          File yourFile = new File(dir, "your/file/path");
          
          if(yourFile.exists())
          {
          
          }
          

          【讨论】:

            【解决方案6】:
            File extStore = Environment.getExternalStorageDirectory();
            File myFile = new File(extStore.getAbsolutePath() + "/book1/page2.html");
            
            if(myFile.exists()){
                ...
            }
            

            这应该可行。

            【讨论】:

              【解决方案7】:
              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
              

              【讨论】:

                猜你喜欢
                • 2011-02-07
                • 2011-10-28
                • 1970-01-01
                • 1970-01-01
                • 2015-06-06
                • 1970-01-01
                • 1970-01-01
                • 2014-03-06
                • 1970-01-01
                相关资源
                最近更新 更多