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

在临时缓存文件android中写入和读取位图时出错?,android,caching,bitmap,fileinputstream,fileoutputstream,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

这是我写入文件时的代码

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


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

我把它改为使用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;
}


非常感谢您回答自己的问题,但是使用Context.MODE_PRIVATE调用openFileOutput()不会在应用程序的缓存目录中创建文件。非常感谢您回答自己的问题,但是使用Context.MODE_PRIVATE调用openFileOutput()不会在应用程序的缓存目录中创建文件。