Matteo Codogno
Matteo Codogno

Reputation: 1579

How to lock, text file open for reading?

I want lock my input text file, in my program, so if the next occurrence of program is run on the same file it crash (throws exception). I know that i can lock file with "java.nio.channels.FileLock" but it's possible only if file is open for writing, and i open text file only for reading. I don't want use "RandomAccessFile" for reading file because is too slow and my file size is very big (10gb). Now i use this wy for reading my file:

FileInputStream fstream = new FileInputStream(this.inputFileName);  
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));  

I think this is fast way to read a text file. How can lock my text input file?

Upvotes: 0

Views: 1050

Answers (1)

Stephen C
Stephen C

Reputation: 719446

I know that i can lock file with "java.nio.channels.FileLock" but it's possible only if file is open for writing,

AFAIK, this is incorrect.

You can acquire a FileLock on a file or a region of a file that you have open for reading. The catch is that this is only guaranteed to prevent another Java application from acquiring an overlapping FileLock. If the other application doesn't attempt to acquire the lock, then it may be able to read the file anyway. (The exact semantics are platform specific.)

Upvotes: 1

Related Questions