2015-07-21 33 views
-4

我試圖用這段代碼檢查一個文件是否存在於我的SD卡上,但我遇到了一些問題。我的Android手機上的API版本是19,應用程序的API版本是19,但是其他應用程序有很多例外,我不想像zedge那樣使用它。請給我一些關於如何檢查該文件是否存在的提示。Android:如何檢查一個文件是否存在於我的SD卡上

public class MainActivity extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    File extStore = Environment.getExternalStorageDirectory(); 
    File myFile = new File(extStore.getAbsolutePath() + "/test.txt"); 

    if(myFile.exists()){ 
     Log.d("File", "exists"); 
    } 

} 


public boolean isExternalStorage() { 
    String state = Environment.getExternalStorageState(); 
    if (Environment.MEDIA_MOUNTED.equals(state)) { 
     return true; 
    } 
    return false; 
} 

}

我的清單文件是這樣的:

<?xml version="1.0" encoding="utf-8"?> 

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

<application 
    android:allowBackup="true" 
    android:icon="@mipmap/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name=".MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
</application> 

+0

你會發現很多鏈接和相同的問題以及他們的解決方案 – Shekhar

+0

你的問題太含糊。您已經在檢查文件是否存在。 「其他應用程序的例外」是什麼意思? –

回答

0

如果文件存在你的代碼只檢查在SD卡/ FILENAME.EXT :

File extStore = Environment.getExternalStorageDirectory(); 
    File myFile = new File(extStore.getAbsolutePath() + "/test.txt"); 

    if(myFile.exists()){ 
     Log.d("File", "exists"); 
    } 

要搜索整個文件系統(目錄樹),我們需要它進入目錄或文件與搜索文件名與遞歸函數:

public static boolean searchForFile(File root, File mySearchFile) 
{ 
    if(root == null || mySearchFile == null) return; //just for safety 

    if(root.isDirectory()) 
    { 
     Boolean flag = false; 
     for(File file : root.listFiles()){ 
      flag = searchForDatFiles(file, mySearchFile); 
      if(flag) return true; 
     } 
    } 
    else if(root.isFile() && root.getName().equals(mySearchFile.getName()) 
    { 
     return true; 
    } 
return false; 
} 

UPDATE

剛看到您只在根文件夾中查找文件。檢查this鏈接有四種方法來檢查文件是否存在。此外,上面的代碼也只適用於SD卡,但不推薦,因爲它會解析首次遇到的任何文件夾。適合整個目錄樹搜索。

+0

好吧,但現在我試圖檢查此文件是否存在硬編碼路徑,因爲稍後我會嘗試加密它。我不需要用給定的名字來搜索文件的entrire系統。 – Metala

+0

我更新了答案 – Kay

相關問題