java.io.IOException: Stream closed解决办法

1.出现这个bug的大体逻辑代码如下:

     private static void findMovieId() throws Exception {
         File resultFile = new File("C:\\2016.txt");
         
         OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(resultFile));
         BufferedWriter bufferWriter = new BufferedWriter(outputStreamWriter);
         
         outputStreamWriter.close();
         bufferWriter.close();
     }

2.报错大体信息如下:

java.io.IOException: Stream closed解决办法_第1张图片

 

 3.解决方式:

原因:

bufferwriter流使用了outputStreamWriter流,所以关闭bufferwriter流也会关闭outputStreamWriter流; 但是下面有使用outputStreamWriter流,相当于使用一个关闭了的流。解决办法是换下位置就可以了.

代码改为:

private static void findMovieId() throws Exception {
        File resultFile = new File("C:\\2016.txt");
        
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(resultFile));
        BufferedWriter bufferWriter = new BufferedWriter(outputStreamWriter);

        bufferWriter.close();        
        outputStreamWriter.close();
    }

同理:FileWriter和BufferWriter之间的关系:

FileWriter fileWriter=new FileWriter(file);
            BufferWriter bufferWriter=new BufferedWriter(fileWriter);

这里关闭流要从大到小关闭,BufferWriter包装了FileWriter,BufferWriter"大",FileWriter"小"
FileWriter.close(); 
BufferWriter.close();
这样的顺序就是不行,FileWriter流自己关闭了。然后BufferWriter流又把FileWriter流关闭一次就会报错java.io.IOException: Stream closed.

你可能感兴趣的:(java基础,Stream,cl)