问题
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