Java FileWriter overwrite

By : kelly
Source: Stackoverflow.com
Question!

I have a piece of code that generates new data whenever there is new data available as InputStream . The same file is overwritten everytime. Sometimes the file becomes 0 kb before it gets written. A webservice reads these files at regular intervals. I need to avoid the case when the file is 0 bytes.

How do it do this? Will locks help in this case? If the browser comes in to read a file which is locked, will the browser continue to show old data from the cache until the lock is released and file is available to be read again.

try{
String outputFile = "output.html";     
FileWriter fWriter = new FileWriter(outputFile);
//write the data ...

fWriter .flush();


outputFile = "anotheroutput.html";     
fWriter = new FileWriter(outputFile);
//write the data ...

fWriter .flush();
fWriter.close();
}
catch(Exception e)
{
 e.prinStackTrace();
}
By : kelly


Answers
public class Data
{
  String fileName;
  protected  Data(String fileName)
  {
     this.fileName= fileName;
     return; // return from constructor often not needed.
  }

   /* above is in some class somehwere 
    *  then your code brings new info to the file
    */

  // 
  public synchronized accessFile(String data)
  {
    try
    {
       // File name to be class member.
       FileWriter fWriter = new FileWriter(fileName);
       //write the data ...
       fWriter.write(data);
       fWriter .flush();
       fWriter .close();
       return;
    }
    catch(Exception e)
    {
       e.prinStackTrace();
    }

this is not needed:

 outputFile = "anotheroutput.html";     
 fWriter = new FileWriter(outputFile);
 //write the data ...

fWriter .flush();
fWriter.close();

that's because work on the file is a method of class Data



Your requirement is not very clear. Do you want to write a new name file every time or you want to append to the same file or you want to over write the same file? Anyway all three cases are easy and from the API you can manage it.

If the issue is that a web service is reading the file which is not yet complete i.e. is in writing phase. In your web service you should check if the file is read only, then only you read the file. In writing phase once writing is finished set the file to read only.

The 0Kb file happens because you are overwriting the same file again. Overwriting cleans up all the data and then start writing the new content.



FileWriter fWriter = new FileWriter(fileName,true);

try using above :-)



This video can help you solving your question :)
By: admin