2017-01-14 75 views
-5

我在評論中使用代碼來保存目錄文件夾中的文件。此代碼可以使用具有SD卡的手機正常工作。我們如何在Android設備存儲中創建應用程序文件夾?

但是,如果我用它沒有SD卡的手機它是給IO異常。 如何創建一個文件夾,如whatsapp在設備存儲根目錄中保存圖像等,但我想要一個應用程序名稱的文件夾來將.csv文件保存在我的設備存儲根目錄中。

+2

術語「設備存儲」未在Android應用程序開發中使用。有[內部存儲](https://commonsware.com/blog/2014/04/07/storage-situation-internal-storage.html),[外部存儲](https://commonsware.com/blog/2014 /04/08/storage-situation-external-storage.html)和[可移動存儲](https://commonsware.com/blog/2014/04/09/storage-situation-removable-storage.html)。 Android SDK中沒有「Environment.getstoragedirectory()」,並且在使用短語「設備存儲」時不明白您指的是什麼。 – CommonsWare

+0

請檢查您的問題,同時張貼在這裏和答案已經在這裏 –

+0

我想有一個像whatsapp文件夾存儲設備存儲圖像bt我必須在該文件夾中存儲.csv文件 –

回答

0

您可以在內部存儲器和外部存儲器中創建目錄,如下所示。

//check whether Sdcard present or not 
Boolean isSDPresent = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED); 

if(isSDPresent) 
{ 
    // yes SD-card is present 
String directory = "/your Directory name or app name "; 
    String path = Environment.getExternalStorageDirectory().getAbsolutePath() + directory; 

    File dir = new File(path); 
    if(!dir.exists())   //check if not created then create the firectory 
        dir.mkdirs(); 

//add your files in directory as follows 
File file = new File(dir, filename); 

} 
else 
{ 
// create folder in internal memory 
File mydir = context.getDir(directory, Context.MODE_PRIVATE); //Creating an internal directry 
    if(!mydir.exists())   //check if not created then create the firectory 
     mydir.mkdirs(); 
    //add your files in directory as follows 

     File file = new File(mydir, filename); 

我希望它會爲你工作

+0

我只做這個,如果我使用我的應用程序在手機上有SD卡它可以正常工作,如果手機沒有SD卡,它會給出錯誤IO期待。 –

+0

我編輯帖子@Sagar_Salal現在檢查它。如果它的工作請你upvote –

+0

我hve更新我的問題,請看看它 –

1

首先讓內部清單

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

確認您已經添加存儲權限如果你想裏面ExternalDirectory

File f = new File(Environment.getExternalStorageDirectory()+"/foldername"); 
if(!f.exists()) f.mkdir(); 
創建文件夾

如果你wa nt在內部存儲器內創建文件

File mydir = context.getDir("mydir", Context.MODE_PRIVATE); //Creating an internal directory; 
File fileWithinMyDir = new File(mydir, "myfile"); 
FileOutputStream out = new FileOutputStream(fileWithinMyDir); 
+0

我wnt有像whatsapp文件夾在設備存儲器中存儲我的文件。 –

+0

然後你應該使用外部存儲方法 – Jayanth

+0

如果你的手機沒有SD卡,你可以告訴我有一個像whatsapp這樣的文件夾的代碼 –

相關問題