【发布时间】:2018-05-15 12:05:26
【问题描述】:
我想在按下按钮时将位图作为 jpg 文件保存到我的 SD 卡。当我运行以下代码时,我没有收到任何错误,但是当我检查手机上的 SD 卡时,没有创建任何文件。我做错了什么?
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
String root = Environment.getExternalStorageDirectory().toString();
//String root = System.getenv("SECONDARY_STORAGE");
File myDir = new File(root + "/Screenshots");
myDir.mkdirs();
Random generator = new Random();
int n = generator.nextInt(10000);
String fname = n+".jpg";
File file = new File(myDir, fname);
Log.d("DD",""+file);
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
rBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
我在清单中有权限,但仍然没有生成文件:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
我做了一些研究表明 getExternalStorageDirectory() 没有给出 SDcard 的路径,但以下替代方法给出了 null:
String root = System.getenv("SECONDARY_STORAGE");
【问题讨论】:
-
为什么要删除文件并保存位图。
-
使用
if (!file.exists()) { file.createNewFile(); } -
如果存在相同的文件名,只需删除现有文件。
-
应该有一个文件,如果你想编辑它。如果您删除现有文件,则该路径中没有文件,因此您无法对其进行编辑。尝试使用上面的代码
-
刚刚尝试过,但仍然没有看到任何文件:尝试 {file.createNewFile(); FileOutputStream out = new FileOutputStream(file); rBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);out.flush();out.close();} catch (Exception e) {e.printStackTrace();}
标签: android android-sdcard android-bitmap