Opening an existing file in Java and closing it.

2019-05-07 10:15发布

问题:

Is it possible to open a file a in java append data and close numerous times. For example:

 //---- psuedocode
      //class variable declaration 
      FileWriter writer1 = new FileWriter(filename);

      fn1:

         writer.append(data - title);

      fn2:
       while(incomingdata == true){
         writer.append(data)
         writer.flush();
         writer.close()
        }

The problem lies in the while loop. The file is closed and cant be opened again. Any one can help me in this?

回答1:

The answers that advise against closing and re-opening the file each time are quite correct.

However, if you absolutely have to do this (and it's not clear to me that you do), then you can create a new FileWriter each time. Pass true as the second argument when you construct a FileWriter, to get one that appends to the file instead of replacing it. Like

FileWriter writer1 = new FileWriter(filename, true); 


回答2:

Once that the file is closed you will need to re-open it. Calling writer.flush() should flush the stream. So basically, you will then remove writer.close() from within the while loop. This will allow you to close the file once that you will have finished with it.

So you have two options, either remove writer.close() from within the while loop or else create a new FileWriter instance at the beginning of your loop.



回答3:

Once a stream has been closed, further write() or flush() invocations will cause an IOException to be thrown. Closing a previously-closed stream, however, has no effect.

 while(incomingdata == true){
         writer.write(data)
 }
 writer.close()

You don't need to flush each time. as calling close() will first flush data before closing the stream.

Updated for

The file that i created has to be saved. For which im supposed to close it so the timestamp is updated. Thats when the file is synced live.

Use it like this

while(incomingdata == true){
             writer.append(data);
             writer.flush();
}
writer.close();


回答4:

I don't recommend trying to close your file and then reopening it again. Opening a file is an expensive operation and the fewer times you do this, the better it is for your code to run quickly.

Open it once, and close the file once you're done writing to it. This would be outside your loop.