Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opening an existing file in Java and closing it.

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?

like image 732
Siddharthan Avatar asked Mar 20 '12 07:03

Siddharthan


People also ask

How do you exit a file in Java?

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.

Can we open an existing file for writing if not why in Java?

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.

Do we need to close file in Java?

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.


3 Answers

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); 
like image 64
Dawood ibn Kareem Avatar answered Nov 14 '22 16:11

Dawood ibn Kareem


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();
like image 37
Anantha Krishnan Avatar answered Nov 14 '22 16:11

Anantha Krishnan


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.

like image 1
Nikhil Avatar answered Nov 14 '22 16:11

Nikhil