首页 > 解决方案 > 如何保存照片?

问题描述

我是 Android 编程新手,还没有找到解决问题的好方法。在我的应用程序中,用户可以从他们的图库中选择照片,然后在 Cardview 布局中用于用户可以自己创建的应用程序中的不同类别。到目前为止,我可以获取所选照片的​​ Uri 并可以显示它。但是如何将照片保存到我的应用程序以确保它始终存在,即使它已从图库中删除?

标签: androiduriphotossaving-data

解决方案


参考:如何在android中制作文件的副本?

要复制文件并将其保存到目标路径,您可以使用以下方法。

public static void copy(File src, File dst) throws IOException {
    InputStream in = new FileInputStream(src);
    try {
        OutputStream out = new FileOutputStream(dst);
        try {
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            out.close();
        }
    } finally {
        in.close();
    }
}

在 API 19+ 上,您可以使用 Java 自动资源管理: public static void copy(File src, File dst) throws IOException { t

ry (InputStream in = new FileInputStream(src)) {
        try (OutputStream out = new FileOutputStream(dst)) {
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        }
    }
}

推荐阅读