LockedFileChannel.java

import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
public class LockedFileChannel implements ByteChannel {
  protected FileChannel fc;
  public LockedFileChannel(FileChannel fc) {
    this.fc = fc;
  }
  public int write(ByteBuffer byteB) throws IOException {
    // Protection par un verrou exclusif
    FileLock fl = fc.lock(fc.position(),byteB.limit(),false);
    try {
      return fc.write(byteB);
    } finally {
      // Libčre le verrou
      fl.release();
    }
  }
  public int read(ByteBuffer byteB) throws IOException {
    // Protection par un verrou partagé
    FileLock fl = fc.lock(fc.position(),byteB.limit(),true);
    try {
      return fc.read(byteB);
    } finally {
      // Libčre le verrou
      fl.release();
    }
  }
  public void close() throws IOException{
    fc.close();
  }
  public boolean isOpen() {
    return fc.isOpen();
  }
}