【发布时间】:2018-08-20 10:27:01
【问题描述】:
我是 Android 编程新手,还没有找到解决问题的好方法。在我的应用程序中,用户可以从他们的图库中选择照片,然后在 Cardview 布局中用于用户可以自己创建的应用程序中的不同类别。到目前为止,我可以获取所选照片的 Uri 并显示它。但是如何将照片保存到我的应用程序以确保它始终存在,即使它已从图库中删除?
【问题讨论】:
标签: android uri photos saving-data
我是 Android 编程新手,还没有找到解决问题的好方法。在我的应用程序中,用户可以从他们的图库中选择照片,然后在 Cardview 布局中用于用户可以自己创建的应用程序中的不同类别。到目前为止,我可以获取所选照片的 Uri 并显示它。但是如何将照片保存到我的应用程序以确保它始终存在,即使它已从图库中删除?
【问题讨论】:
标签: android uri photos saving-data
参考:How to make a copy of a file in 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 自动资源管理: 公共静态无效副本(文件 src,文件 dst)抛出 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);
}
}
}
}
【讨论】: