2016-07-25 115 views
0

我知道類似的問題已經在這裏問了很多,但我找不到適合我的答案。將圖像/視頻文件保存到子文件夾中的應用程序內部存儲器

我有一個文件對象有一個指向SD卡(外部存儲)的路徑。例如:

File selectedFile = new File("/storage/emulated/0/Pictures/Screenshots/Screenshot_20160725-185624.png"); 

我想現在要做的就是到圖像/視頻保存到我的應用程序的內部存儲的子文件夾。

例如,將文件保存到這裏: INTERNAL_STORAGE/20/public_gallery/300.png

當我使用

outputStream = context.openFileOutput("20/public_gallery/300.png", Context.MODE_PRIVATE); 
... 
outputStream.write(content.getBytes()); 
... 

我不能使用任何我的問題是, 「/」爲子文件夾。

如果任何人都可以提供給我一個小代碼示例,我將非常感激。

+0

只需使用絕對路徑和FileOutputStream即可。 – greenapps

+0

'SD卡(外部存儲)'。不可以。一個micro SD卡是可移動存儲器。 – greenapps

+0

'/ storage/emulated/0/......'。這是外部存儲。與微型SD卡無關。 – greenapps

回答

0

試試這個:

path = Environment.getExternalStorageDirectory() + "/your_app_folder" + "/any_subfolder/" + "filename.extension" 
file = new File(destFilePath); 
FileOutputStream out = null; 
try { 
    out = new FileOutputStream(file); 
    ... 
} catch (Exception e) { 
    e.printStackTrace(); 
} finally { 
    if(out!=null) { 
     out.close(); 
    } 
} 

「/」 不應該是一個問題,我猜。

0

在辦公室的一個項目中找到解決方案。

下面是關於如何將文件保存到用戶已經用一個文件瀏覽器對話框中選擇的內部存儲工作的完整示例:

public boolean copyFileToPrivateStorage(File originalFileSelectedByTheUser, Contact contact) { 

    File storeInternal = new File(getFilesDir().getAbsolutePath() + "/76/public"); // "/data/user/0/net.myapp/files/76/public" 
    if (!storeInternal.exists()) { 
     storeInternal.mkdirs(); 
    } 
    File dstFile = new File(storeInternal, "1.png"); // "/data/user/0/net.myapp/files/76/public/1.png" 

    try { 
     if (originalFileSelectedByTheUser.exists()) { 
      // Now we copy the data of the selected file to the file created in the internal storage 
      InputStream is = new FileInputStream(originalFileSelectedByTheUser); 
      OutputStream os = new FileOutputStream(dstFile); 
      byte[] buff = new byte[1024]; 
      int len; 
      while ((len = is.read(buff)) > 0) { 
       os.write(buff, 0, len); 
      } 
      is.close(); 
      os.close(); 

      return true; 
     } else { 
      String error = "originalFileSelectedByTheUser does not exist"; 
      return false; 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
     return false; 
    } 
} 

它需要的文件「originalFileSelectedByTheUser」,也就是在某處外部存儲(如Screenshots目錄),並將其副本保存到內部存儲「dstFile」中的位置,以便只有應用程序可以訪問該文件。

相關問題