• Post Reply Bookmark Topic Watch Topic
  • New Topic

Check whether a file is being read while trying to overwrite it.  RSS feed

 
Rudy Rusli
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

In JAVA, is there anyway I can check whether a file is being read while trying to overwrite it. I have a JAVA program that overwrites a huge file every 5 minutes, but it seems to give problems to our clients when reading the file exactly the same time when it is being overwritten.

Thanks in advance for all the help.
 
Galen Palmer
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I believe this is more a OS issue than a Java specific issue. What I would do in the situation is build the new file and move it to replace the previous version. If nothing else, the time where the state of the file is in flux would be much smaller. The downside, is that for a few moments you would have 2 copies of your file until the move takes place.

// create a temporary file
File f = new File("/files/huge_file.bck");

// your method to write to the file...
populateHugeFile(f);

if(!f.renameTo(new File("/files/huge_file.txt")) {
// renaming failed; try again?
}

Even this has risks however. From the API:

Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists.
 
Rudy Rusli
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply.

I'll do some testing.
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Won't you be getting an IOException if you try writing to a file which is "open" ?
 
Rudy Rusli
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Based on my testing, no IOException is thrown.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!