Opening an existing file in Java and closing it.

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

//---- 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 is the while loop. The file is closed and cannot be reopened. Can anyone help me with this?

+4
source share
4 answers

The answers that advise you not to close and reopen the file each time are perfectly correct.

However, if you absolutely must do this (and it is not clear that you are doing this), you can create a new FileWriter each time. Pass true as the second argument when you create the FileWriter to get the one that is added to the file instead of replacing it. how

 FileWriter writer1 = new FileWriter(filename, true); 
+2
source

Once the file is closed, you will need to open it again. A writer.flush() call should clear the stream. So basically you remove the writer.close() from the while . This will allow you to close the file as soon as you are done with it.

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

+1
source

Once the stream is closed, subsequent calls to write () or flush () will throw an IOException. However, closing a previously closed stream is not affected.

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

You do not need to rinse every time. since calling close() will clear the data first before closing the stream.

Updated for

The file I created must be saved. Why do they close it to update the timestamp. That when the file is synchronized live.

Use it like this:

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

I do not recommend trying to close the file and then open it again. Opening a file is an expensive operation, and the less you do it, the better it is to quickly run your code.

Open it once and close the file as soon as you finish writing. This will be outside of your loop.

0
source

Source: https://habr.com/ru/post/1402376/


All Articles