0

我知道类似的问题已经在这里问了很多,但我找不到适合我的答案。

我有一个 File 对象,它有一个指向 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());
...

我不能对子文件夹使用任何“/”。

如果有人能给我一个小代码示例,我将非常感激。

4

2 回答 2

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;
    }
}

它获取外部存储(例如 Screenshots 目录)中某处的文件“originalFileSelectedByTheUser”,并将其副本保存到内部存储中“dstFile”中的位置,以便只有应用程序可以访问该文件。

于 2016-07-29T21:11:49.190 回答
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();
    }
}

我猜“/”应该不是问题。

于 2016-07-25T20:56:50.783 回答