How to create Image File inside Internal Cache Directory in Android

陌路散爱 提交于 2021-02-11 09:51:32

问题


I want to have image.png inside cache/images/ in Internal Storage of Android.

I am not able to have it with following code:

File directory = new File(getContext().getCacheDir(), "images");
directory.mkdirs();


File mypath=new File(directory,"image.png");

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(mypath);

    bmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (Exception e) {
    e.printStackTrace();
} finally {
    try {
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}       

With the above code I am not even able to create a directory named images. Pls help, I am beginner.


回答1:


Try this:

File sd = getCacheDir();
            File folder = new File(sd, "/myfolder/");
            if (!folder.exists()) {
                if (!folder.mkdir()) {
                    Log.e("ERROR", "Cannot create a directory!");
                } else {
                    folder.mkdirs();
                }
            }

            File fileName = new File(folder,"mypic.jpg");

            try {
                        FileOutputStream outputStream = new FileOutputStream(String.valueOf(fileName));
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                        outputStream.close();

                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }


来源:https://stackoverflow.com/questions/41733663/how-to-create-image-file-inside-internal-cache-directory-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!