从文件夹中删除缓存的图像

时间:2014-06-19 19:18:31

标签: android android-activity

我目前将从互联网上下载的图像保存到磁盘。我希望能够在用户关闭应用程序时删除图像。我想将图像全部保存在一个文件夹中,以便删除它们。我做了getActivity().getCacheDir().getAbsolutePath()+ File.separator + "newfoldername"来获取文件夹的路径。不确定如何将图像添加到文件夹中。

public void saveImage(Context context, Bitmap b, String name_file, String path) {
    FileOutputStream out;
    try {
        out = context.openFileOutput(name_file, Context.MODE_PRIVATE);
        b.compress(Bitmap.CompressFormat.JPEG,90, out);
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public Bitmap getImageBitmap(Context context, String name) {
    try {
        FileInputStream fis = context.openFileInput(name);
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize =  1;
        Bitmap  b =   BitmapFactory.decodeStream(fis,null, options);
        b.getAllocationByteCount());
        fis.close();
        return b;
    } catch (Exception e) {}
    return null;
}

1 个答案:

答案 0 :(得分:1)

您不应将图像保存在缓存文件夹中,因为您不能依赖文档来依赖它。更好的方法是将它们存储在SD卡上。根据文件:

public abstract File getCacheDir()

返回文件系统上特定于应用程序的缓存目录的绝对路径。这些文件将在设备运行不足时首先被删除。无法保证何时删除这些文件。注意:您不应该依赖系统为您删除这些文件;对于缓存文件占用的空间量,应始终具有合理的最大值(例如1 MB),并在超过该空间时修剪这些文件。

FOR SAVING

private String saveToInternalSorage(Bitmap bitmapImage){
    File directory = getApplicationContext().getDir("MY_IMAGE_FOLDER"
    ,Context.MODE_PRIVATE);

    File mypath=new File(directory,"profile.jpg");
    FileOutputStream fos = null;
    try {           
        fos = new FileOutputStream(mypath);
        bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
        fos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return directory.getAbsolutePath();
}

FOR READING

private void loadImageFromStorage(String path)
{
    try {
        File file = new File(path, "Image.jpg");
        Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
        ImageView img = (ImageView)findViewById(R.id.my_imgView);
        img.setImageBitmap(bitmap);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

FOR DELETING:

String dir = getApplicationContext().getDir("MY_IMAGE_FOLDER"
    ,Context.MODE_PRIVATE);
if (dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            new File(dir, children[i]).delete();
        }
    }
相关问题