Check if a file is open before reading it?

后端 未结 2 838
长发绾君心
长发绾君心 2021-01-24 19:55

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 th

相关标签:
2条回答
  • 2021-01-24 20:36

    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();
    }
    
    0 讨论(0)
  • 2021-01-24 20:39

    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
    0 讨论(0)
提交回复
热议问题