java-重置BufferedInputStream保留一个FileInputStream

我分两个步骤解码jpeg.

>检查边界,必要时确定比例.
>在屏幕限制内解码.

public static Bitmap decodeSampledBitmapFromInputStream(InputStream data, int reqWidth, int reqHeight)
{
    // First decode with inJustDecodeBounds=true to check dimensions
    final BitmapFactory.Options options = new BitmapFactory.Options();
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(data, null, options);

    // Calculate inSampleSize
    options.inSampleSize = Util.getExactSampleSize(options, reqWidth, reqHeight);

    // Decode bitmap with inSampleSize set
    options.inJustDecodeBounds = false;

    try {
        // TODO: This works, but is there a better way?
        if (data instanceof FileInputStream)
            ((FileInputStream)data).getChannel().position(0);
        else
            data.reset();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

    return BitmapFactory.decodeStream(data, null, options);
}

当基础流是FileInputStream时,它将在reset()上崩溃,并带有:

java.io.IOException: Mark has been invalidated.

因此,我添加了instanceof部分以手动重置FileInputStreams的位置,但这似乎是一个很尴尬的解决方案.有没有办法正确重置封装FileInputStream的BufferedInputStream?

解决方法:

使用InputStream.reset之前,必须先调用InputStream.mark,以标记要稍后返回的位置.

上一篇:怎么提高字节流传输效率?BufferedInputStream有一个方法readAllBytes()可提高很多


下一篇:java-BufferedInputStream如何使读取操作更快?