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

来源:互联网 发布:icc 文件 mac 编辑:程序博客网 时间:2024/05/27 16:43

在写一个保存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 提示,但是目前好像还是可以用的。

阅读全文
0 0
原创粉丝点击