1.出现这个bug的大体逻辑代码如下:
1 private static void findMovieId() throws Exception { 2 File resultFile = new File("C:\\2016.txt"); 3 4 OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream(resultFile)); 5 BufferedWriter bufferWriter = new BufferedWriter(outputStreamWriter); 6 7 outputStreamWriter.close(); 8 bufferWriter.close(); 9 }
2.报错大体信息如下:
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.
本文转自SummerChill博客园博客,原文链接:http://www.cnblogs.com/DreamDrive/p/7389672.html,如需转载请自行联系原作者