2014-03-19 37 views
2

我想在SD卡,使目錄,我也跟着:的Android mkdirs()SD卡不工作

  1. 我說:<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />清單中。
  2. 我得到root_path通過:public static final String ROOT_PATH = Environment.getExternalStorageDirectory().toString() + "/Hello_World/";它返回 /storage/emulated/0/Hello_World(得到時調試)。

接下來,運行此代碼:

File file = new File(Constants.ROOT_PATH); 
int i = 0; 
while (!file.isDirectory() && !file.mkdirs()) { 
    file.mkdirs(); 
    Log.e("mkdirs", "" + i++); 
} 

我也都嘗試mkdirs()mkdir()但它顯示的logcat(Log.e("mkdirs", "" + i++);)無限循環。有時它有效,但有時不會。 感謝您的幫助!
Update:我嘗試了一些設備的代碼:Nexus4,nexus7,Vega Iron,Genymotion,LG G Pro,然後Vega Iron按預期工作。 ?? !!?!?

+0

冉你的代碼讓它安裝在設備中。現在從計算機上拔下並運行您的應用程序。而不是Log.e顯示敬酒。 –

+0

@HoanNguyen我試過,但沒有幫助:( – Justin

+0

)您將不得不更加具體地瞭解所遇到的問題。在您的問題中編輯一個「logcat無限循環」示例。 –

回答

3

嘗試這樣就會在創建一個文件夾sd card

String root = Environment.getExternalStorageDirectory().toString(); 
File myDir = new File(root + "/hello_world");  
myDir.mkdirs(); 

如果你想檢查文件是否存在或不使用t他的代碼

File file = new File (myDir, file_name); 
if (file.exists()) 
    // file exist 
else 
    // file not exist 

僅供參考看看這個答案Android saving file to external storage

+0

我不知道什麼是不同的btw你的溶劑和我的?//它仍然不工作:( – Justin

+0

它會在SD卡中創建一個文件夾..那麼你的期望? –

+0

我的代碼,我嘗試在sdcard上創建一個名爲Hello_World的文件夾,並且有時它可以工作,有時不會:( – Justin

0

使用Environment.getExternalStorageDirectory().getAbsolutePath()如下...

​​

,並檢查SD卡,如下創建目錄之前安裝....

File file = new File(Constants.ROOT_PATH); 
int i = 0; 

if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { 
     if(!file.exists()) { 
      file.mkdir(); 
     } 
} 
+0

感謝您的回答,但它仍然返回'/ storage/emulated/0/Hello_World'仍然不起作用順便說一句,我想知道你爲什麼編輯我的文章(我很難閱讀)和-1我?Tks again! – Justin

+0

看到更新的答案。 –

+0

我看到和改變,但沒有什麼變化:( – Justin

1

錯誤原因是由while (!file.isDirectory() && !file.mkdirs())&&應該while (!file.isDirectory() || !file.mkdirs())。您還應該檢查媒體是否已安裝。

if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) 
    { 
     if (DEBUG) {Log.d(TAG, "createSoundDir: media mounted");} //$NON-NLS-1$ 
     File externalStorage = Environment.getExternalStorageDirectory(); 
     if (externalStorage != null) 
     { 
      String externalStoragePath = externalStorage.getAbsolutePath(); 
      File soundPathDir = new File(externalStoragePath + File.separator + "Hello_World"); //$NON-NLS-1$ 

      if (soundPathDir.isDirectory() || soundPathDir.mkdirs()) 
      { 
       String soundPath = soundPathDir.getAbsolutePath() + File.separator; 
       if (DEBUG) {Log.d(TAG, "soundPath = " + soundPath);} //$NON-NLS-1$ 

      } 
     } 
    } 

從我的一個項目中剪切和粘貼。

1

謝謝你們所有人,最後我發現了這個問題。問題是在while()循環,我通過

替換如果 (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) & &!file.isDirectory()){
file.mkdirs() ;
}

+0

您的問題的可能部分是mkdirs()只在創建目錄時返回true,而不是在它已存在時返回。 –