2016-10-18 29 views
2

我正在使用链接列表。该node类(链接列表)是这样的:为什么BufferedWriter第二次不打印数据?

public class node { 
    String data; 
    node next; 
    node previous; 
} 

stack类,它使用node类,我写了一个方法print()打印值,print()是象下面这样:

void print() throws IOException{ 
     try(BufferedWriter print=new BufferedWriter(new OutputStreamWriter(System.out))){ 
      node temp=this.getFirstNode(); 
      while(temp!=null){ 
       print.write(temp.getData()); 
       temp=temp.getNext(); 
      } 
      print.close(); 
     } 
    } 

当我创建stack类的两个实例并调用print()时,它仅打印第一个实例的data。例如,在下面的代码不会打印Bdata

public static void main(String[] args) { 
     stack A=new stack(); 
     stack B=new stack(); 
     A.print(); 
     B.print(); 
    } 

我已经搜查了很多,调试了好几次,它完美地运行。但不知道为什么第二次不打印出data

+1

我大胆猜测,你调用'打印。 close()关闭默认输出流'System.out',一旦它关闭,你就不能重新打开它。 –

+0

@ d.j.brown它不像每个实例的一个流?这是所有实例使用它的一般流? – HMD

+0

'System.out'是'System'类中的一个静态字段,由每个使用它的类/对象共享。改用'print.flush()',不要关闭流。 –

回答

4

您已经关闭System.out,这是您通常不应该做的事情。当使用在try-与资源的语法通常是Java中的最佳实践,与System.out打交道时,它只是冗余(读:通常是错误的):

void print() throws IOException{ 
    BufferedWriter print = new BufferedWriter(new OutputStreamWriter(System.out)); 
    node temp = this.getFirstNode(); 
    while(temp != null){ 
     print.write(temp.getData()); 
     temp = temp.getNext(); 
    } 
}