@Override
  public int write(ByteBuffer src) throws IOException {
    checkNotNull(src);
    checkOpen();
    checkWritable();

    int written = 0; // will definitely either be assigned or an exception will be thrown

    synchronized (this) {
      boolean completed = false;
      try {
        if (!beginBlocking()) {
          return 0; // AsynchronousCloseException will be thrown
        }
        file.writeLock().lockInterruptibly();
        try {
          if (append) {
            position = file.size();
          }
          written = file.write(position, src);
          position += written;
          file.setLastModifiedTime(fileSystemState.now());
          completed = true;
        } finally {
          file.writeLock().unlock();
        }
      } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
      } finally {
        endBlocking(completed);
      }
    }

    return written;
  }
@Test
  public void testWrite() throws IOException {
    RegularFile file = regularFile(0);
    FileChannel channel = channel(file, WRITE);
    assertEquals(0, channel.position());

    ByteBuffer buf = buffer("1234567890");
    ByteBuffer buf2 = buffer("1234567890");
    assertEquals(10, channel.write(buf));
    assertEquals(10, channel.position());

    buf.flip();
    assertEquals(20, channel.write(new ByteBuffer[] {buf, buf2}));
    assertEquals(30, channel.position());

    buf.flip();
    buf2.flip();
    assertEquals(20, channel.write(new ByteBuffer[] {buf, buf2}, 0, 2));
    assertEquals(50, channel.position());

    buf.flip();
    assertEquals(10, channel.write(buf, 5));
    assertEquals(50, channel.position());
  }