android - 向临时缓存文件android写入和读取位图时出错?

标签 android caching bitmap fileinputstream fileoutputstream

这是我写入文件时的代码

Bitmap bitmap;
InputStream is;

try
{
    is = (InputStream) new URL(myUrl).getContent();
    bitmap = BitmapFactory.decodeStream(is);
    is.close();

     //program crashing here
    File f = File.createTempFile(myUrl,null,MyApplication.getAppContext().getCacheDir());
    FileOutputStream fos = new FileOutputStream(f);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    fos.flush();
    fos.close();
}
catch(Exception e)
{
    bitmap = null;
}

这是我从同一个文件读取的代码

Bitmap bitmap;
try
{
    File f = new File(myUrl);
    FileInputStream fis = new FileInputStream(f);
    BufferedInputStream bis = new BufferedInputStream(fis);
    byte[] bitmapArr = new byte[bis.available()];
    bis.read(bitmapArr);
    bitmap = BitmapFactory.decodeByteArray(bitmapArr, 0, bitmapArr.length);
    bis.close();
    fis.close();
}
catch(Exception e)
{
    bitmap = null;
}

程序在第一段代码中创建临时文件时崩溃。

编辑:我得到一个 libcore.io.ErrnoException

最佳答案

更新:我发现了问题并修复了它,任何有兴趣的人请看下面。

我将其更改为使用 openFileOutput(String, int) 和 openFileInput(String) 方法,我应该从一开始就这样做。

以下是工作代码,用于将包含图像的 url 中的输入流解码为位图,压缩位图并将其存储到文件中,稍后从该文件中检索所述位图。

Bitmap bitmap;
InputStream is;

try
{
    is = (InputStream) new URL(myUrl).getContent();
    bitmap = BitmapFactory.decodeStream(is);
    is.close();

    String filename = "file"
    FileOutputStream fos = this.openFileOutput(filename, Context.MODE_PRIVATE);
    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
    fos.close();
}
catch(Exception e)
{
    bitmap = null;
}

Bitmap bitmap;

try
{
    String filename = "file";
    FileInputStream fis = this.openFileInput(filename);
    bitmap = BitmapFactory.decodeStream(fis);
    fis.close();
}
catch(Exception e)
{
    bitmap = null;
}

关于android - 向临时缓存文件android写入和读取位图时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18090721/

相关文章:

java - Android:具有两个不同 View 的 EfficientAdapter

android - 如何在 Android 中创建文本输入对话框?

android - 获取 Facebook SDK NuGet 时出错

java - 在多台机器上管理 EhCache

delphi - 为什么“Bitmap.SaveToFile”导致黑屏

java - Android向非常大的jpg文件添加水印 Logo (例如10000 x 150000)

java - 从 android 中的 onTouchEvent 获取 X 和 Y 值

javascript - 为了让浏览器知道始终使用缓存,我应该设置什么响应 header ?

caching - ColdFusion ORM 如何处理 ORM 外部所做的更改

android - 如何使用刚刚从图库中选择或从相机捕获的图像填充 gridview