1

Here is my code when I am writing to the file

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

And here is my code reading from the same file

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

The program is crashing at the creation of the temp file in the first chunk of code.

EDIT: I am getting a libcore.io.ErrnoException

4

1 回答 1

1

更新:我发现了问题并修复了它,有兴趣的人请参见下文。

我将其更改为使用 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;
}
于 2013-08-07T07:52:47.470 回答