sadhu
sadhu

Reputation: 1479

Deny read access to a file till the write is complete - java

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?

Upvotes: 3

Views: 1081

Answers (4)

Pavan Kumar K
Pavan Kumar K

Reputation: 1376

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

Upvotes: 0

JIV
JIV

Reputation: 823

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.

Upvotes: 4

Ian Roberts
Ian Roberts

Reputation: 122364

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"));

Upvotes: 6

Djon
Djon

Reputation: 2260

You can use the FileLock API.

I explained briefly how it works here.

Upvotes: 1

Related Questions