java IO Exception: Stream Closed

前端 未结 3 1016
臣服心动
臣服心动 2020-12-06 16:29

This is the code I currently have:

public class FileStatus extends Status{
FileWriter writer;
public FileStatus(){
    try {
        writer = new FileWriter(         


        
相关标签:
3条回答
  • 2020-12-06 16:46

    You call writer.close(); in writeToFile so the writer has been closed the second time you call writeToFile.

    Why don't you merge FileStatus into writeToFile?

    0 讨论(0)
  • 2020-12-06 16:50

    You're calling writer.close(); after you've done writing to it. Once a stream is closed, it can not be written to again. Usually, the way I go about implementing this is by moving the close out of the write to 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();
        }
    }
    

    And add a method cleanUp to close the stream.

    public void cleanUp() {
         writer.close();
    }
    

    This means that you have the responsibility to make sure that you're calling cleanUp when you're done writing to the file. Failure to do this will result in memory leaks and resource locking.

    EDIT: You can create a new stream each time you want to write to the file, by moving writer into the writeToFile() method..

     public void writeToFile() {
        FileWriter writer = new FileWriter("status.txt", true);
        // ... Write to the file.
    
        writer.close();
     }
    
    0 讨论(0)
  • 2020-12-06 16:56

    Don't call write.close() in writeToFile().

    0 讨论(0)
提交回复
热议问题