2011-08-01 102 views
1

我有一個Android mkdirs()返回false。我讀了另一個回答,你有一個類似的問題。你提到了一些關於Environment.getExternal的東西......反正我在Droid X上運行Android 2.2.SD卡是掛載的,並且兩個返回值都是可讀的,並且iswritable返回true。這裏是我的代碼...Android mkdirs()返回false

public void writeToExternalStoragePublic(String filename, byte[] content) { 

    // API Level 7 or lower, use getExternalStorageDirectory() 
    // to open a File that represents the root of the external 
    // storage, but writing to root is not recommended, and instead 
    // application should write to application-specific directory, as shown below. 

    String packageName = this.getPackageName(); 
    Toast.makeText(this, packageName, 1000).show(); 
    String path = "/Android/data/";// + packageName + "/files/"; 

    if (isExternalStorageAvailable() && 
     !isExternalStorageReadOnly()) { 
     try { 
      File file = new File(path, filename); 
      file.mkdirs(); 
      file.mkd 
      Toast.makeText(this, "Made Dirs = " + file.mkdirs(), 1000).show(); 
      Toast.makeText(this, "Made Dir = " + file.mkdir(), 1000).show(); 

      FileOutputStream fos = new FileOutputStream(file); 
      fos.write(content); 
      fos.close(); 
      Toast.makeText(this, "success", 1000).show(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
      Toast.makeText(this, "fnf", 1000).show(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
      Toast.makeText(this, "io", 1000).show(); 
     } catch (SecurityException e) { 
      Toast.makeText(this, "security", 1000).show(); 
     } 
    } 
} 

謝謝。如果你知道任何方式,我可以得到它mkdirs我會很感激。謝謝。

此代碼實際上是來自其他人的示例,我試圖使其工作。

http://www.ibm.com/developerworks/xml/library/x-androidstorage/index.html

d-RAN

回答

2

File.mkdirs()只會返回true一次:當目錄實際上已經被創建。從文檔:

如果必需的目錄已創建,則返回true;如果目標目錄已存在或者其中一個目錄不能創建,則返回false。

因此,除非您刪除該目錄,否則每隔一次都會返回false()。如果您想知道該目錄是否存在,請使用File.isDirectory()

FWIW,我沒有DroidX,所以我無法說出您正在使用的路徑,但該路徑無法在設備上運行有。我還建議檢查路徑(使用ADB shell)以確保您嘗試創建的路徑是有效的路徑。

+1

確實,這不是一個有效的路徑。請參閱http://developer.android.com/guide/topics/data/data-storage.html#AccessingExtFiles但是請注意,在那裏推薦getExternalStorageDirectory()用於較舊的API版本需要對具有多個存儲卷的設備進行特殊處理(「內部「/外部SD等) –