0 votes
16 views
in Java by (9.5k points)

This is the code I currently have:

public class FileStatus extends Status{

FileWriter writer;

public FileStatus(){

    try {

        writer = new FileWriter("status.txt",true);

    } catch (IOException e) {

        e.printStackTrace();

    }

}

public void writeToFile(){

    String file_text= pedStatusText + "     " + gatesStatus + "     " + DrawBridgeStatusText;

    try {

        writer.write(file_text);

        writer.flush();

        writer.close();

    } catch (IOException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    }

}

}

My code works fine, but when it calls the writeToFile method for the second time I get the following:

   

java.io.IOException: Stream closed

Even though the file is written to the second time, it always throws the above error whenever I give a call to writeToFile(). Can anyone tell me how to resolve this error?

1 Answer

0 votes
by (19.7k points)

You should not call writer.close(), after you are writing to it since the stream is closed. You can implement the below code to move close out of the write method:

public void writeToFile(){

    String file_text= pedStatusText + "     " + gatesStatus + "     " + DrawBridgeStatusText;

    try {

        writer.write(file_text);

        writer.flush();

    } catch (IOException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    }

}

Also you can add method cleanUp to close the stream:

public void cleanUp() {

     writer.close();

}

Interested in Java? Check out this Java Certification by Intellipaat.    

Welcome to Intellipaat Community. Get your technical queries answered by top developers !

Categories

...