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?
Java FileOutputStream close() Method. The close() method of FileOutputStream class is used to close the file output stream and releases all system resources associated with this stream.
It will automatically create a new file if the file doesn't exist or overwrite an existing file if it exists: FileOutputStream out = new FileOutputStream("filename. xyz"); out. write(data, 0, data.
You never have to close File s, because it is basically a representation of a path. Only Streams and Readers/Writers. In fact, File does not even have a close() method.
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);
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With