2

I have a requirement where in I write a file to server. Another application has a scheduled job which reads the file at a specific interval. The file shouldn't be readable till my write is complete. I have tried using

File.isReadable(false)

But this is not working. And the scheduler is picking up the incomplete data from the file, if I am still writing to it.

Any Solutions?

sadhu
  • 1,429
  • 8
  • 14
  • How about [getting a lock on the file](http://stackoverflow.com/questions/128038/how-can-i-lock-a-file-using-java-if-possible)? – MD Sayem Ahmed May 29 '13 at 12:13

4 Answers4

5

Write to a different file name and then when the write is complete rename the file to the name the scheduler expects. If you're running on Linux or similar then file renames within the same file system are atomic.

File tempFile = new File("/path/to/file.tmp");
// write to tempFile
tempFile.renameTo(new File("/path/to/file"));
Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
  • If you're using Java 7, better use the new `Files` API. – Djon May 29 '13 at 12:17
  • @Ian My app runs on windows. The App reading the file is on Solaris. And the file server is Linux. Meaning the file and the apps are on different physical machines – sadhu May 29 '13 at 12:23
  • @sadhu it may still be worth a try, or if you have control over the app reading the file then [JIV's answer](http://stackoverflow.com/a/16813659/592139) is probably the best way to go. – Ian Roberts May 29 '13 at 12:39
  • This is a smart, simple and reliable solution that should work in almost any scenario. I like it. Can only +1 unfortunately. – Durandal May 29 '13 at 12:42
  • @Ian I am already on it. Will update the forum once I am through. Yes, I do have control on both the apps. – sadhu May 29 '13 at 12:54
  • @Ian JIV's answer worked well. I should have already thought about it as Autosys FileWatcher jobs does the same:) – sadhu May 29 '13 at 13:02
4

You can use another file with same name as marker. You will start writing into FileName.txt and when is finished, create file FileName.rdy
And your application will check only for *.rdy files, if found - read FileName.txt.

JIV
  • 813
  • 2
  • 12
  • 30
1

You can use the FileLock API.

I explained briefly how it works here.

Community
  • 1
  • 1
Djon
  • 2,230
  • 14
  • 19
0

the better option would be to synchronize the read and write procedures...

put your code to read file and write file in synchornized {} blocks....such that one can wait till other completes

Pavan Kumar K
  • 1,360
  • 9
  • 11