當前位置: 首頁>>代碼示例>>Java>>正文


Java WritableByteChannel類代碼示例

本文整理匯總了Java中java.nio.channels.WritableByteChannel的典型用法代碼示例。如果您正苦於以下問題:Java WritableByteChannel類的具體用法?Java WritableByteChannel怎麽用?Java WritableByteChannel使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


WritableByteChannel類屬於java.nio.channels包,在下文中一共展示了WritableByteChannel類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: validate

import java.nio.channels.WritableByteChannel; //導入依賴的package包/類
/**
 * Gets a part of the given URL, writes the content into the given channel.
 * Fails if the returned HTTP status is not "206 partial content".
 *
 * @param <IWC> a generic type for any class that implements InterruptibleChannel and WritableByteChannel
 * @param url to get
 * @param output written with the content of the HTTP response
 * @param etag value of the If-Range header
 * @param range_start range byte start (inclusive)
 * @param range_end range byte end (inclusive)
 *
 * @return a response (contains the HTTP Headers, the status code, ...)
 *
 * @throws IOException IO error
 * @throws InterruptedException interrupted
 * @throws RuntimeException containing the actual exception if it is not an instance of IOException
 */
public <IWC extends InterruptibleChannel & WritableByteChannel>
      HttpResponse interruptibleGetRange(String url, final IWC output, String etag, long range_start, long range_end)
      throws IOException, InterruptedException
{
   HttpGet get = new HttpGet(url);
   get.setHeader("If-Range", etag);
   get.setHeader("Range", String.format("bytes=%d-%d", range_start, range_end));
   // This validator throws an IOException if the response code is not 206 partial content
   ResponseValidator val = new ResponseValidator()
   {
      @Override
      public void validate(HttpResponse response) throws HttpException, IOException
      {
         if (response.getStatusLine().getStatusCode() != HttpStatus.SC_PARTIAL_CONTENT)
         {
            throw new IOException("Range request does not return partial content");
         }
      }
   };
   return interruptibleRequest(get, output, val);
}
 
開發者ID:SentinelDataHub,項目名稱:dhus-core,代碼行數:39,代碼來源:InterruptibleHttpClient.java

示例2: write

import java.nio.channels.WritableByteChannel; //導入依賴的package包/類
/**
 * {@inheritDoc}
 */
@Override
public void write(WritableByteChannel channel) throws IOException {
    logger.config(getLoggingFilename() + ":Writing tag to channel");

    byte[] bodyByteBuffer = writeFramesToBuffer().toByteArray();
    logger.config(getLoggingFilename() + ":bodybytebuffer:sizebeforeunsynchronisation:" + bodyByteBuffer.length);

    //Unsynchronize if option enabled and unsync required
    unsynchronization = TagOptionSingleton.getInstance().isUnsyncTags() && ID3Unsynchronization.requiresUnsynchronization(bodyByteBuffer);
    if (isUnsynchronization()) {
        bodyByteBuffer = ID3Unsynchronization.unsynchronize(bodyByteBuffer);
        logger.config(getLoggingFilename() + ":bodybytebuffer:sizeafterunsynchronisation:" + bodyByteBuffer.length);
    }
    ByteBuffer headerBuffer = writeHeaderToBuffer(0, bodyByteBuffer.length);

    channel.write(headerBuffer);
    channel.write(ByteBuffer.wrap(bodyByteBuffer));
}
 
開發者ID:openaudible,項目名稱:openaudible,代碼行數:22,代碼來源:ID3v22Tag.java

示例3: fastCopy

import java.nio.channels.WritableByteChannel; //導入依賴的package包/類
/**
     * copy
     *
     * @param src
     * @param dest
     * @throws IOException
     */
    public static void fastCopy(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException {
        final ByteBuffer buffer = ByteBuffer.allocateDirect(8 * 1024);
        int count = 0;

        while ((count = src.read(buffer)) != -1) {
//            LogUtil.d("luaviewp-fastCopy", count, buffer.capacity(), buffer.remaining(), buffer.array().length);
            // prepare the buffer to be drained
            buffer.flip();
            // write to the channel, may block
            dest.write(buffer);
            // If partial transfer, shift remainder down
            // If buffer is empty, same as doing clear()
            buffer.compact();
        }
        // EOF will leave buffer in fill state
        buffer.flip();
        // make sure the buffer is fully drained.
        while (buffer.hasRemaining()) {
            dest.write(buffer);
        }
    }
 
開發者ID:alibaba,項目名稱:LuaViewPlayground,代碼行數:29,代碼來源:ChannelTools.java

示例4: sendAck

import java.nio.channels.WritableByteChannel; //導入依賴的package包/類
/**
 * send a reply-acknowledgement (6,2,3), sends it doing a busy write, the ACK is so small
 * that it should always go to the buffer
 * @param key
 * @param channel
 */
protected void sendAck(SelectionKey key, WritableByteChannel channel, byte[] command, SocketAddress udpaddr) {
    try {

        ByteBuffer buf = ByteBuffer.wrap(command);
        int total = 0;
        if (channel instanceof DatagramChannel) {
            DatagramChannel dchannel = (DatagramChannel)channel;
            //were using a shared channel, document says its thread safe
            //TODO check optimization, one channel per thread?
            while ( total < command.length ) {
                total += dchannel.send(buf, udpaddr);
            }
        } else {
            while ( total < command.length ) {
                total += channel.write(buf);
            }
        }
        if (log.isTraceEnabled()) {
            log.trace("ACK sent to " +
                    ( (channel instanceof SocketChannel) ?
                      ((SocketChannel)channel).socket().getInetAddress() :
                      ((DatagramChannel)channel).socket().getInetAddress()));
        }
    } catch ( java.io.IOException x ) {
        log.warn("Unable to send ACK back through channel, channel disconnected?: "+x.getMessage());
    }
}
 
開發者ID:sunmingshuai,項目名稱:apache-tomcat-7.0.73-with-comment,代碼行數:34,代碼來源:NioReplicationTask.java

示例5: readStreamAsStr

import java.nio.channels.WritableByteChannel; //導入依賴的package包/類
/**
 * 將流轉換為字符串
 *
 * @param is
 * @return
 * @throws IOException
 */
public static String readStreamAsStr(InputStream is) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    WritableByteChannel dest = Channels.newChannel(bos);
    ReadableByteChannel src = Channels.newChannel(is);
    ByteBuffer bb = ByteBuffer.allocate(4096);

    while (src.read(bb) != -1) {
        bb.flip();
        dest.write(bb);
        bb.clear();
    }
    src.close();
    dest.close();

    return new String(bos.toByteArray(), Constants.ENCODING);
}
 
開發者ID:linkingli,項目名稱:FaceDistinguish,代碼行數:24,代碼來源:HttpUtil.java

示例6: ArrayOutputAdapter

import java.nio.channels.WritableByteChannel; //導入依賴的package包/類
/**
 * Constructs an adapter for the specified channel, output, and byte order.
 * If not null, the writable byte channel enables more efficient writes.
 * @param channel the writable byte channel; null, if none.
 * @param output the data output.
 * @param order the byte order.
 */
public ArrayOutputAdapter(
  WritableByteChannel channel, DataOutput output, ByteOrder order) 
{
  _wbc = channel;
  _do = output;
  _bo = order;
  if (_wbc!=null) {
    _bb = ByteBuffer.allocateDirect(4096);
  } else {
    _buffer = new byte[4096];
    _bb = ByteBuffer.wrap(_buffer);
  }
  if (order==ByteOrder.BIG_ENDIAN) {
    _bb.order(ByteOrder.BIG_ENDIAN);
  } else {
    _bb.order(ByteOrder.LITTLE_ENDIAN);
  }
  _cb = _bb.asCharBuffer();
  _sb = _bb.asShortBuffer();
  _ib = _bb.asIntBuffer();
  _lb = _bb.asLongBuffer();
  _fb = _bb.asFloatBuffer();
  _db = _bb.asDoubleBuffer();
}
 
開發者ID:MinesJTK,項目名稱:jtk,代碼行數:32,代碼來源:ArrayOutputAdapter.java

示例7: execute

import java.nio.channels.WritableByteChannel; //導入依賴的package包/類
/**
 * execute.
 * @param cmd - cmd
 * @throws IOException - IOException
 */
@Override
public void execute(Command cmd) throws IOException {
    Path filePath = Paths.get(cmd.getParam());
    if (Files.exists(filePath, LinkOption.NOFOLLOW_LINKS)
            && !Files.isDirectory(filePath) && Files.isReadable(filePath)) {

        System.out.println("Uploading...");

        ObjectOutputStream oos = new ObjectOutputStream(outputStream);
        oos.writeObject(cmd);
        oos.flush();

        WritableByteChannel rbc = Channels.newChannel(new DataOutputStream(outputStream));
        FileInputStream fis = new FileInputStream(cmd.getParam());
        fis.getChannel().transferTo(0, Long.MAX_VALUE, rbc);
        rbc.close();

        System.out.println("Done.");
    } else {
        System.out.println("Error. Please try again.");
    }
}
 
開發者ID:istolbov,項目名稱:i_stolbov,代碼行數:28,代碼來源:CommandFactoryClient.java

示例8: sendAck

import java.nio.channels.WritableByteChannel; //導入依賴的package包/類
/**
 * send a reply-acknowledgement (6,2,3), sends it doing a busy write, the
 * ACK is so small that it should always go to the buffer
 * 
 * @param key
 * @param channel
 */
protected void sendAck(SelectionKey key, WritableByteChannel channel, byte[] command, SocketAddress udpaddr) {
	try {

		ByteBuffer buf = ByteBuffer.wrap(command);
		int total = 0;
		if (channel instanceof DatagramChannel) {
			DatagramChannel dchannel = (DatagramChannel) channel;
			// were using a shared channel, document says its thread safe
			// TODO check optimization, one channel per thread?
			while (total < command.length) {
				total += dchannel.send(buf, udpaddr);
			}
		} else {
			while (total < command.length) {
				total += channel.write(buf);
			}
		}
		if (log.isTraceEnabled()) {
			log.trace("ACK sent to "
					+ ((channel instanceof SocketChannel) ? ((SocketChannel) channel).socket().getInetAddress()
							: ((DatagramChannel) channel).socket().getInetAddress()));
		}
	} catch (java.io.IOException x) {
		log.warn("Unable to send ACK back through channel, channel disconnected?: " + x.getMessage());
	}
}
 
開發者ID:how2j,項目名稱:lazycat,代碼行數:34,代碼來源:NioReplicationTask.java

示例9: getContentOutputStream

import java.nio.channels.WritableByteChannel; //導入依賴的package包/類
/**
 * @see Channels#newOutputStream(java.nio.channels.WritableByteChannel)
 */
public OutputStream getContentOutputStream() throws ContentIOException
{
    try
    {
        WritableByteChannel channel = getWritableChannel();
        OutputStream is = new BufferedOutputStream(Channels.newOutputStream(channel));
        // done
        return is;
    }
    catch (Throwable e)
    {
        throw new ContentIOException("Failed to open stream onto channel: \n" +
                "   writer: " + this,
                e);
    }
}
 
開發者ID:Alfresco,項目名稱:alfresco-repository,代碼行數:20,代碼來源:AbstractContentWriter.java

示例10: transferTo

import java.nio.channels.WritableByteChannel; //導入依賴的package包/類
@Override
public long transferTo(WritableByteChannel target, long position) throws IOException {
    if (this.byteBufferHeader.hasRemaining()) {
        transferred += target.write(this.byteBufferHeader);
        return transferred;
    } else {
        List<ByteBuffer> messageBufferList = this.queryMessageResult.getMessageBufferList();
        for (ByteBuffer bb : messageBufferList) {
            if (bb.hasRemaining()) {
                transferred += target.write(bb);
                return transferred;
            }
        }
    }

    return 0;
}
 
開發者ID:lirenzuo,項目名稱:rocketmq-rocketmq-all-4.1.0-incubating,代碼行數:18,代碼來源:QueryMessageTransfer.java

示例11: getBox

import java.nio.channels.WritableByteChannel; //導入依賴的package包/類
public void getBox(WritableByteChannel os) throws IOException {
    ByteBuffer bb = ByteBuffer.allocate(l2i(getSize()));
    getHeader(bb);
    if (content == null) {
        getContent(bb);
        if (deadBytes != null) {
            deadBytes.rewind();
            while (deadBytes.remaining() > 0) {
                bb.put(deadBytes);
            }
        }
    } else {
        content.rewind();
        bb.put(content);
    }
    bb.rewind();
    os.write(bb);
}
 
開發者ID:lisnstatic,項目名稱:live_master,代碼行數:19,代碼來源:AbstractBox.java

示例12: getBox

import java.nio.channels.WritableByteChannel; //導入依賴的package包/類
public void getBox(WritableByteChannel writableByteChannel) throws IOException {
    ByteBuffer bb = ByteBuffer.allocate(16);
    long size = getSize();
    if (isSmallBox(size)) {
        IsoTypeWriter.writeUInt32(bb, size);
    } else {
        IsoTypeWriter.writeUInt32(bb, 1);
    }
    bb.put(IsoFile.fourCCtoBytes("mdat"));
    if (isSmallBox(size)) {
        bb.put(new byte[8]);
    } else {
        IsoTypeWriter.writeUInt64(bb, size);
    }
    bb.rewind();
    writableByteChannel.write(bb);
}
 
開發者ID:fishwjy,項目名稱:VideoCompressor,代碼行數:18,代碼來源:MP4Builder.java

示例13: transferTo

import java.nio.channels.WritableByteChannel; //導入依賴的package包/類
@Override
public long transferTo(WritableByteChannel target, long position) throws IOException {
    if (this.byteBufferHeader.hasRemaining()) {
        transfered += target.write(this.byteBufferHeader);
        return transfered;
    }
    else {
        List<ByteBuffer> messageBufferList = this.queryMessageResult.getMessageBufferList();
        for (ByteBuffer bb : messageBufferList) {
            if (bb.hasRemaining()) {
                transfered += target.write(bb);
                return transfered;
            }
        }
    }

    return 0;
}
 
開發者ID:y123456yz,項目名稱:reading-and-annotate-rocketmq-3.4.6,代碼行數:19,代碼來源:QueryMessageTransfer.java

示例14: transferTo

import java.nio.channels.WritableByteChannel; //導入依賴的package包/類
/**
 * This code is more complicated than you would think because we might require multiple
 * transferTo invocations in order to transfer a single MessageWithHeader to avoid busy waiting.
 *
 * The contract is that the caller will ensure position is properly set to the total number
 * of bytes transferred so far (i.e. value returned by transfered()).
 */
@Override
public long transferTo(final WritableByteChannel target, final long position) throws IOException {
  Preconditions.checkArgument(position == totalBytesTransferred, "Invalid position.");
  // Bytes written for header in this call.
  long writtenHeader = 0;
  if (header.readableBytes() > 0) {
    writtenHeader = copyByteBuf(header, target);
    totalBytesTransferred += writtenHeader;
    if (header.readableBytes() > 0) {
      return writtenHeader;
    }
  }

  // Bytes written for body in this call.
  long writtenBody = 0;
  if (body instanceof FileRegion) {
    writtenBody = ((FileRegion) body).transferTo(target, totalBytesTransferred - headerLength);
  } else if (body instanceof ByteBuf) {
    writtenBody = copyByteBuf((ByteBuf) body, target);
  }
  totalBytesTransferred += writtenBody;

  return writtenHeader + writtenBody;
}
 
開發者ID:spafka,項目名稱:spark_deep,代碼行數:32,代碼來源:MessageWithHeader.java

示例15: transferTo

import java.nio.channels.WritableByteChannel; //導入依賴的package包/類
@Override
public long transferTo(WritableByteChannel target, long position)
    throws IOException {
  if (manageOsCache && readaheadPool != null) {
    readaheadRequest = readaheadPool.readaheadStream(identifier, fd,
        getPosition() + position, readaheadLength,
        getPosition() + getCount(), readaheadRequest);
  }
  
  if(this.shuffleTransferToAllowed) {
    return super.transferTo(target, position);
  } else {
    return customShuffleTransfer(target, position);
  } 
}
 
開發者ID:naver,項目名稱:hadoop,代碼行數:16,代碼來源:FadvisedFileRegion.java


注:本文中的java.nio.channels.WritableByteChannel類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。