同一Inputstream的父类和子类对象请维持最具体的子类对象,不要混合使用

来源:互联网 发布:知乎 张雪健 编辑:程序博客网 时间:2024/06/08 01:10

1 致谢


2 问题描述

今天在进行进行Android编程 使用来源于同一个网络流的两个InputStream对象 
private BufferedInputStream bis = null;private InputStream is;……bis = new BufferedInputStream(is);……

在编程时 为了方便 
将来源于同一网络流的BufferedInputStream和InputStream交替使用来获取数据
……if (bis.read(buf) != len)……if (!DecUtils.get_one_ADTS_frame(bis, arrayList_AACData)) {……

在编程时 到一个很奇怪的问题用它们的read()函数读取同一段数据的结果竟然不同
代码分别如下:
使用BufferedInputStream
/**     * 读取2字节数据并转换为int型     * 使用BufferedInputStream     *     * @return     */    private int readInt() {        byte[] buf = new byte[2];        int res = 0;        try {            if (bis.read(buf) != 2)                throw new IOException("no more data!!!");            System.out.println("readInt() " +buf[0]+"and"+buf[1]);            res = (buf[0] & 0x000000FF) | (((int) buf[1]) << 8);        } catch (IOException e) {            e.printStackTrace();        }        return res;    }

其结果是:


使用InputStream
private int readIntTest() {        byte[] buf = new byte[2];        int res = 0;        try {            is.read(buf,0,2);            System.out.println("readIntTest() " +buf[0]+"and"+buf[1]);            res = (buf[0] & 0x000000FF) | (((int) buf[1]) << 8);        } catch (IOException e) {            e.printStackTrace();        }        return res;    }
其结果是:


可以发现两个函数的结果是不同的 这实际上是十分奇怪的
因为从逻辑上分析 两种InputStream的read()函数提供的功能是一致的
所以结果应该是相同的
我也写了一段代码进行验证 代码如下
static public void main(String[] args) {// is的测试替换代码        String path = "C:\\Users\\玉成\\Desktop\\2017-12-22-13-39-33-986__8286.3da";        try {            InputStream is = new FileInputStream(new File(path));            byte[] buf=new byte[2];            is.read(buf,0,2);            System.out.println("readIntTest()"+(short)buf[0]+","+(short)buf[1]);            is.close();                        is = new FileInputStream(new File(path));            BufferedInputStream bis = new BufferedInputStream(is);            bis.read(buf);            System.out.println("readInt() " +buf[0]+"and"+buf[1]);            bis.close();            is.close();        } catch (IOException e) {            e.printStackTrace();        }                System.out.println("Hello Java.");}

其结果为


这也说明了两个InputStream的read()函数提供的功能是一致的
所以肯定是前面的某个地方出现了问题
后来我觉得肯定是由于交替使用两种InputStream的read()函数导致的

3 解决方案

在使用InputStream和其子类对象时 仅维持其最具体的子类对象
以InputStream和BufferedInputStream为例
如果存在类似于继承的关系 如来源于同一数据流 例如 网络流或者文件流
就仅维持其最具体的子类对象 如BufferedInputStream
如果需要使用InputStream作为参数 则直接使用利用BufferedInputStream子类的多态性质即可
在这次编程中 我把is作为了形参
而把BufferedInputStream作为成员变量 于是只维护了这一个具体的子类对象

4 测试


测试成功

阅读全文
0 0