您的位置:首页 > 移动开发 > Android开发

Android中使用file.createNewFile()无法创建文件的问题(例如保存拍照的图片到本地)

2017-11-08 17:12 696 查看
在写一个保存bitmap文件的方法的时候,遇到了题中问题。

为了不出现问题,不要直接

File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/myfoodphoto/" + path);
f.createNewFile();

这样写会出现not found such file ...

首先先mkdir()创建根文件夹myfoodphoto,再使用file.createNewFile(),就可以了。

还需要权限

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" />

public String saveBitmap(Bitmap mBitmap) {
String sdStatus = Environment.getExternalStorageState();
if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
Toast.makeText(this, "内存卡异常,请检查内存卡插入是否正确", Toast.LENGTH_SHORT).show();
return "";
}
String path = System.currentTimeMillis() + ".jpg";
File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/myphoto/");
if (!f.exists()) {
f.mkdir();
}
File file = new File(f, path);
try {
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
return file.getAbsolutePath();
} catch (IOException e) {
e.printStackTrace();
return null;
}


还有就是该方法会出现ignore this method 提示,但是目前好像还是可以用的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 图片 文件io
相关文章推荐