2017-07-28 151 views
0

我知道這是一個雙後,但其他線程沒有回答我的問題。 我想要寫一個文件到我的Android的目錄中的應用程序的目錄中的內部存儲android - 保存文件到內部存儲

我加了權限清單:

的Manifest.xml代碼:

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

的Java代碼

File myPath = new File(getFilesDir(), "test.dat");    
    myPath.mkdirs(); 
    FileOutputStream fos = null; 
    try { 
     fos = new FileOutputStream(myPath); 
     fos.write(bytes); 
    } catch (Exception e) { 

    } 

然而,我的應用程序目錄沒有創建,我無法通過搜索找到文件名。

編輯: 實際上有一個FileNotFoundException拋出,我的壞。 但我認爲mkdirs()會創建所有缺少的目錄。

+1

使用運行時權限https://developer.android.com/training/permissions/requesting.html – Anil

+1

內部存儲不需要運行時權限 –

+1

你可以做e.printStackTrace();在你的例外,看看有什麼問題 –

回答

1

您可以通過以下嘗試:

ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext()); 
    File directory = contextWrapper.getDir(getFilesDir().getName(), Context.MODE_PRIVATE); 
    File file = new File(directory,」fileName」); 
    String data = 「TEST DATA」; 
    FileOutputStream fos = new FileOutputStream(「fileName」, true); // save 
    fos.write(data.getBytes()); 
    fos.close(); 

這將寫入設備的內部存儲(/data/user/0/com.yourapp/)

希望這有助於文件!

1

嘗試這種方式

String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/filename"; 

      File dir = new File(path); 
      if (!dir.exists()) 
       dir.mkdirs(); 

      // File file = new File(dir, "filename"); 
+0

這可能會工作,但是是一種不同的方法。要存儲在內部存儲器中,絕對路徑後不需要有文件夾結構。這並不能告訴他他犯了什麼錯誤。 –

+0

你可以直接寫文件名而不是它會起作用,試試看看我編輯的答案文件會在你的內部存儲器上創建 –

+0

我試了一下,結果相同 - > FileNotFoundException – cmplx96

1

但未創建和我無法找到通過搜索文件名我的應用程序的目錄。

你,作爲一個用戶,有你的應用程序的部分沒有獲得什麼了Android SDK是指爲internal storage,這是你使用的是什麼

用戶可以訪問哪些Android SDK的external storage