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()',不要關閉流。 –