android - 如何保存照片?
问题描述
我是 Android 编程新手,还没有找到解决问题的好方法。在我的应用程序中,用户可以从他们的图库中选择照片,然后在 Cardview 布局中用于用户可以自己创建的应用程序中的不同类别。到目前为止,我可以获取所选照片的 Uri 并可以显示它。但是如何将照片保存到我的应用程序以确保它始终存在,即使它已从图库中删除?
解决方案
要复制文件并将其保存到目标路径,您可以使用以下方法。
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);
}
}
}
}
推荐阅读
- r - 分配全局/反应变量
- java - 如何等待所有按钮点击功能完成
- swift - 为什么我在 draw 中创建的 CAShapeLayer 没有成功设置动画?
- python - 如果两列具有相同的字符串或列为空,则从 python 中的 postgres 表中获取行
- http - Flutter 中的 API 访问问题
- javascript - 即使输入了错误的凭据 Passport.js 登录功能也不会产生任何错误并使用户通过身份验证
- bash - 如何发送 1kk post http 请求。最快的方法是什么?
- python - 有没有办法优化熊猫中连接表的创建?
- javascript - 无法更新 React Js 表单中的状态值
- jquery - 错误消息的顺序以反映 Jquery 验证中输入字段的顺序