2016-07-25 114 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”中的位置,以便只有应用程序可以访问该文件。

相关问题