这是我写入文件时的代码
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/