【问题标题】:How to create Image File inside Internal Cache Directory in Android如何在 Android 的内部缓存目录中创建图像文件
【发布时间】:2017-01-19 04:18:22
【问题描述】:

我想在 Android 的内部存储中的 cache/images/ 中有 image.png。

我无法使用以下代码:

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

使用上面的代码,我什至无法创建一个名为 images 的目录。请帮忙,我是初学者。

【问题讨论】:

  • 你添加权限了吗?
  • 我在清单中添加了 。但我认为内部存储不需要该权限。
  • 是什么让您认为您无法创建名为 images 的目录?你有例外吗?

标签: android android-file


【解决方案1】:

试试这个:

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

【讨论】:

  • 成功了。谢谢。我两次都错过了“/”。
  • Log.e("ERROR", "Cannot create a directory!");。您应该在此处添加 return; 语句,因为尝试在不存在的目录中创建文件是没有意义的。
  • else { folder.mkdirs(); }。您还应该检查 mkdirs() 的返回值。为什么要使用 mkdir() 和 mkdirs()?单独使用 Mkdirs() 就可以了。
  • @greenapps 去学习编码的基础知识。或者在你的应用上涂上绿色!
【解决方案2】:

我是这样实现的……

//create file
File file = new File(context.getExternalCacheDir(), System.currentTimeMillis() + ".png");

//draw image if created successfully
if (file.createNewFile()) {

//initialize image BitMap
Bitmap bitmap = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);

//initialize canvas and paint object
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.LINEAR_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);

//design part goes here using Paint and Canvas
...

//get file output stream and draw design on image file
FileOutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
}

【讨论】:

    猜你喜欢
    • 2017-12-28
    • 2012-06-08
    • 2022-08-19
    • 1970-01-01
    • 2020-05-22
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    相关资源
    最近更新 更多