java里的File.createNewFile遇到的坑

需求:将bitmap保存到sdcard,遇到的问题保存失败

因为是别人的项目,临时帮忙给改bug,这是之前的工具类,最后抛异常了

public static void savePic(Bitmap b,File imgFile) {
        if (b == null || imgFile == null){
            return;
        }
        FileOutputStream fos;
        try {
            imgFile.createNewFile();
            fos = new FileOutputStream(imgFile);
            b.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

createNewFile
假如file的路径是 /a/b/demo.png,如果/a/b文件夹不存在的话会抛出异常,因此在使用的时候需要判断该文件的父文件夹是否存在,不存在的话需要先创建

修改之后的方法:

public static void savePic(Bitmap b,File imgFile) {
        if (b == null || imgFile == null){
            return;
        }
        if (imgFile.getParentFile() != null && !imgFile.getParentFile().exists()) {
            imgFile.getParentFile().mkdirs();
        }
        FileOutputStream fos;
        try {
            imgFile.createNewFile();
            fos = new FileOutputStream(imgFile);
            b.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(Java,安卓)