Exemple #1
0
    @Override
    public void write(byte[] bytes, int off, int len) throws IOException {
      if (bytes == null) {
        throw new NullPointerException("null source buffer");
      }
      if ((len | off | (off + len) | (bytes.length - (off + len))) < 0) {
        throw new IndexOutOfBoundsException();
      }

      try {
        synchronized (stream) {
          if (!stream.isSync() && stream.bufferedOutputSpaceRemaining() >= len) {
            stream.buffer.put(bytes, off, len);

          } else if (stream.getDescriptor().getChannel() instanceof SelectableChannel) {
            SelectableChannel ch = (SelectableChannel) stream.getDescriptor().getChannel();
            synchronized (ch.blockingLock()) {
              boolean oldBlocking = ch.isBlocking();
              try {
                if (!oldBlocking) {
                  ch.configureBlocking(true);
                }
                stream.bufferedWrite(ByteBuffer.wrap(bytes, off, len));
              } finally {
                if (!oldBlocking) {
                  ch.configureBlocking(oldBlocking);
                }
              }
            }
          } else {
            stream.bufferedWrite(ByteBuffer.wrap(bytes, off, len));
          }
        }
      } catch (BadDescriptorException ex) {
        throw new IOException(ex.getMessage());
      }
    }