Nate
Nate

Reputation: 28374

Check if a file is open before reading it?

I'm trying to make an applet that reads a file on the local file system (the users computer) at a very frequent interval (several times a second), then makes the contents of the file available to the web page via javascript.

The file the applet needs to read is updated at a high frequency by a program on the user's computer. What I'm concerned about is what might happen if the applet reads data from the file when the file is in the middle of being updated.

I don't know how likely this is, but if it is a valid concern is there a way to make sure the file is not currently being written to before reading it?

Upvotes: 1

Views: 2701

Answers (2)

Jess
Jess

Reputation: 25069

I'm not positive about this, but you could try java.io.FileInputStream, or some other option from that package.

Also, this question may be a duplicate. This might answer your question:

  1. How do I use Java to read from a file that is actively being written?
  2. reading a file while it's being written
  3. Read a file while it's being written
  4. Reading data from a File while it is being written to

Upvotes: 2

internals-in
internals-in

Reputation: 5038

its very monster to make such a disk access, any way try Sockets if you can or if again you sits back try to lock file in both ends if the one of the locking fails then make sure that other is locking ,make up this to your use

File file = new File(fileName);
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
// Get an exclusive lock on the whole file
FileLock lock = channel.lock();
try {
    lock = channel.tryLock();
    // Ok. You get the lock
} catch (OverlappingFileLockException e) {
    // File is open by other end 
} finally {
    lock.release();
}

Upvotes: 1

Related Questions