The pit encountered by File.createNewFile in java

Requirement: Save the bitmap to sdcard, the problem encountered is that the save fails

Because it is someone else's project, temporarily help to fix the bug, this is the previous tool class, and finally throws an exception

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
If the path of the file is /a/b/demo.png, if the /a/b folder does not exist, an exception will be thrown, so when using it, it is necessary to determine whether the parent folder of the file exists. If it does not exist, it needs to create first

The modified method:

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();
        }
    }

Guess you like

Origin blog.csdn.net/qq_36356379/article/details/107044331