java文件流的关闭问题

  1. writer =new BufferedWriter(new OutputStreamWriter(out));
  2. OutputStreamWriter outstr = new OutputStreamWriter(out); writer =new BufferedWriter(outstr); writer和out这两个文件流需要关闭我晓得。可是第一个案例new OutputStreamWriter 这个new出来的流我没有实例化,这样写合理吗,还是说像第二个案例这样关闭三个流。第一种会不会造成流不关闭情况。有人晓得不。

1 题目中writer和out这两个流构成流链(stream chain),在这种情况下,只需要关闭最上层的流(此例中为writer),链中的其它流会自动关闭。
2 如题目所示,有两种写法:

Something s = new Something(); //如果你在之后并不需要用 s 这个变量,那么此种写法和下面写法没有区别
Other o = new Other(s);

Other o = new Other(new Something()); //如前所述,如果不需要使用s,那么这种写法更为简洁,也更常用。

回到题目,基本程序逻辑如下即可:

writer =new BufferedWriter(new OutputStreamWriter(out));
//其它代码
writer.close(); //关闭最上层流,流链中其它流会自动关闭。

如果对您有帮助,请采纳答案好吗,谢谢!

流的使用你要记住几个层级的,,不要把嵌套在里面的流关掉而导致外部的流无法运作,,所哟你开启一个流就尽量使用一个流,,开启了不使用很浪费空间,,,还有最后用完一定要close掉,,要不然它会一直占用。

比如下面的代码片段:

ObjectInputStream input = new ObjectInputStream(new FileInputStream("a.txt"));
User us= (User) input.readObject();
input.close();

看ObjectInputStream的构造器:

public ObjectInputStream(InputStream in) throws IOException {
    ...
    bin = new BlockDataInputStream(in);//重点
}

看ObjectInputStream的close()方法:

public void close() throws IOException {
    ...
    bin.close();//重点
}

看BlockDataInputStream构造器:

BlockDataInputStream(InputStream in) {
    this.in = new PeekInputStream(in);//重点
    ...
}

看BlockDataInputStream的close()方法:

public void close() throws IOException {
    ...
    in.close();//重点
}

看PeekInputStream的构造器:

PeekInputStream(InputStream in) {
    this.in = in;
}

看PeekInputStream的close()方法:

public void close() throws IOException {
    in.close();//执行FileInputStream的close方法
}

上面的in都是FileInputStream,说明被包装的FileInputStream的流也会被自动调用close()方法