java.io.IOException:stream closed 异常的原因及处理

一、close 顺序异常

FileInputStream inputStream = null;
try {
    inputStream = new FileInputStream("tst.txt");
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream, 1024);

try {
    // 错误顺序,可能出现java.io.IOException:stream closed异常
    inputStream.close();
    bufferedInputStream.close();

    // 正确顺序应该为
    bufferedInputStream.close();
    inputStream.close();
} catch (IOException e) {
    e.printStackTrace();
}

二、文件输入流和缓存流不在同一个线程

public class MyTestClass {
    FileInputStream mInputStream;

    public MyTestClass() {

        try {
            mInputStream = new FileInputStream("test.h264");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {

                BufferedInputStream bufferedInputStream = new BufferedInputStream(mInputStream, 1024);

                byte[] buffer = new byte[1024];
                try {
                    // 调用read接口时可能出现java.io.IOException:stream closed异常
                    // 这是由于bufferedInputStream是在子线程中定义的,而mInputStream是在主线程中定义的
                    int len = bufferedInputStream.read(buffer, 0, 1024);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
}

应该更改为:

public class MyTestClass {        

        public MyTestClass() {

            new Thread(new Runnable() {
                FileInputStream mInputStream;
                
                @Override
                public void run() {

                    try {
                        mInputStream = new FileInputStream("test.h264");
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(mInputStream, 1024);

                    byte[] buffer = new byte[1024];
                    try {
                        int len = bufferedInputStream.read(buffer, 0, 1024);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

你可能感兴趣的:(Android)