Search code examples
javabufferedwriter

Why BufferedWriter doesn't print data for the 2nd time?


I am using a linked-list. The node class (for the linked-list) is like this:

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

In class stack, which uses node class, I've written a method print() to print values, print() is like below:

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();
        }
    }

When I create 2 instances of stack class and call print(), it just prints the data of 1st instance. For example in below code it doesn't print B's data:

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

I've searched a lot and debugged it several times, it runs perfectly. but couldn't figure out why it doesn't print out data for the second time.


Solution

  • You've closed System.out, which is something you shouldn't usually do. While using the try-with-resource syntax is usually the best practice in Java, when dealing with System.out it's just redundant (read: usually wrong):

    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();
        }
    }