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
。例如,在下面的代码不会打印B
的data
:
public static void main(String[] args) {
stack A=new stack();
stack B=new stack();
A.print();
B.print();
}
我已经搜查了很多,调试了好几次,它完美地运行。但不知道为什么第二次不打印出data
。
我大胆猜测,你调用'打印。 close()关闭默认输出流'System.out',一旦它关闭,你就不能重新打开它。 –
@ d.j.brown它不像每个实例的一个流?这是所有实例使用它的一般流? – HMD
'System.out'是'System'类中的一个静态字段,由每个使用它的类/对象共享。改用'print.flush()',不要关闭流。 –