2013-03-21 108 views
-6

這是將資產複製到SD卡的code在Android中創建目錄

但是,它僅將文件複製到根目錄。如果我的代碼更改爲這一點,那麼該文件將被複制到mydirectory中,但條件是,「mydirectory中」必須先手動創建:

Environment.getExternalStorageDirectory() + "/mydirectory/" 
            + files[i]); 

我的問題是我應該如何修改代碼以使新的目錄可以創建?我發現this,並遇到了創建文件對象和使用mkdirs()

但是我真的不知道如何做到這一點,因爲我是新的android開發,並沒有編程的先驗知識。

我希望如果有人能給我一步一步的指導如何實現這一點。

謝謝。

+0

您已經有您所提供的鏈接的答案。 – 2013-03-21 13:30:30

+0

http://stackoverflow.com/questions/15517247/how-to-create-a-directory-in-external-sd-in-android-application/15517312#15517312。檢查這個鏈接。 – Raghunandan 2013-03-21 13:50:22

+0

是的,我知道在提供的鏈接有答案,但問題是我不知道如何實施它沒有一步一步的指導。我對編程一無所知。希望你能幫助。 – user2190227 2013-03-21 14:49:19

回答

1

您必須在開始添加文件(顯然)之前創建目錄。

在試圖複製所謂「資產」的文件中使用此項。查看評論:

String filename = Environment.getExternalStorageDirectory() + "/mydirectory/"); // this sets the filename of the new dir 
File newDir = new File (filename); // this creates the File object (no directory yet) 
if (!newDir.exists()) // here we check whether the dir is already there 
    newDir.mkdirs() // if not, then create all necessary directories and subdirectories to our new dir 
+0

我可以簡單地把File newDir = new File(filename);根據上面的代碼?我把它放在一個錯誤,這是文件名不能解析爲變量?我通過自學學習了Android開發。如果你能提供一步一步的指導,我真的很感激。 – user2190227 2013-03-21 13:37:36

+0

不,請參閱我向代碼添加了聲明。另外,我上次沒有完成該帖子。看到我上面的編輯。 – Shade 2013-03-21 14:15:51

+0

如果你能告訴我爲此需要採取的全部步驟,我將非常感激。例如,我應該把你的代碼放在哪裏?應該添加什麼? – user2190227 2013-03-21 17:08:29

0

它可以幫助你..

boolean success = (new File("/sdcard/dirname")).mkdir(); 
if (!success) 
{ 
    Log.w("directory not created", "directory not created"); 
}