android - 当尝试将 byteArray 写入文件时,它会转换 0B png 文件,无法获取有效文件
问题描述
val downloadDir = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), getString(R.string.app_name))
if (!downloadDir.isDirectory) { //Creates directory named by this file downloadDir.mkdirs() } val file = File(downloadDir, fileName) try { val ostream = FileOutputStream(file) ostream.write(imageByteArray) ostream.flush() ostream.close() }
解决方案
我正在使用以下代码将用户的头像保存在sdcard
. 您可以更改代码以满足您的需求:
public static String copyToAppDirectory(Context c, Uri uri, String personID) throws IOException {
File src = new File(uri.getPath());
File mediaStorageDir = new File(Environment.getExternalStorageDirectory(), BaseConst.AppDir);
mediaStorageDir = new File(mediaStorageDir, BaseConst.ImageFolder);
File dst = new File(mediaStorageDir, personID + ".JPG");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
throw new IOException("Cannot create Directory!");
}
}
InputStream in;
try {
in = c.getContentResolver().openInputStream(uri);
} catch (Exception ex) {
in = new FileInputStream(src);
}
try {
OutputStream out = new FileOutputStream(dst);
try {
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
} finally {
out.close();
}
} finally {
in.close();
}
return dst.getPath();
}
希望对你有帮助
推荐阅读
- powershell - [tag]已解决[/tag] 无法在 Powershell 命令中使用我的变量作为 Powershell Studio 中的 GUI
- python - 在条形堆栈图中标记和操作每个堆栈
- android - 如何从项目的strings.xml 列表中读取ViewModel 数据
- javascript - 如何在 html 日历中导入谷歌日历事件?
- sql - 使用 cte 时获得额外的日期
- c# - 为什么我在 web api HttpPost 方法中使用 [FromBody] 属性时得到 405 Unsopported media type?
- javascript - 使用 mongodb 的搜索查询使用 $or 返回一个结果
- amazon-web-services - AWS CloudWatch 触发时自动重置 (OK) 警报
- ios - Unity iOS 构建中莫名其妙的错误
- android - 每次拒绝位置权限后都会重新加载片段