java.nio.ByteBuffer.allocate()方法的使用及代码示例

x33g5p2x  于2022-01-16 转载在 其他  
字(7.4k)|赞(0)|评价(0)|浏览(564)

本文整理了Java中java.nio.ByteBuffer.allocate()方法的一些代码示例,展示了ByteBuffer.allocate()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ByteBuffer.allocate()方法的具体详情如下:
包路径:java.nio.ByteBuffer
类名称:ByteBuffer
方法名:allocate

ByteBuffer.allocate介绍

[英]Creates a byte buffer based on a newly allocated byte array.
[中]基于新分配的字节数组创建字节缓冲区。

代码示例

代码示例来源:origin: google/guava

/**
 * Flips the buffer output buffer so we can start reading bytes from it. If we are starting to
 * drain because there was overflow, and there aren't actually any characters to drain, then the
 * overflow must be due to a small output buffer.
 */
private void startDraining(boolean overflow) {
 byteBuffer.flip();
 if (overflow && byteBuffer.remaining() == 0) {
  byteBuffer = ByteBuffer.allocate(byteBuffer.capacity() * 2);
 } else {
  draining = true;
 }
}

代码示例来源:origin: iluwatar/java-design-patterns

/**
 * Reads and returns {@link ByteBuffer} from the underlying {@link SocketChannel} represented by
 * the <code>key</code>. Due to the fact that there is a dedicated channel for each client
 * connection we don't need to store the sender.
 */
@Override
public ByteBuffer read(SelectionKey key) throws IOException {
 SocketChannel socketChannel = (SocketChannel) key.channel();
 ByteBuffer buffer = ByteBuffer.allocate(1024);
 int read = socketChannel.read(buffer);
 buffer.flip();
 if (read == -1) {
  throw new IOException("Socket closed");
 }
 return buffer;
}

代码示例来源:origin: apache/flink

@Override
public byte[] serialize() {
  final int size = Integer.BYTES + content.length;
  return ByteBuffer.allocate(size)
      .putInt(content.length)
      .put(content)
      .array();
}

代码示例来源:origin: apache/incubator-druid

private void convertToMutableByteBuffer()
{
 ByteBuffer tmpBuffer = ByteBuffer.allocate(storageBuffer.remaining());
 tmpBuffer.put(storageBuffer.asReadOnlyBuffer());
 tmpBuffer.position(0);
 storageBuffer = tmpBuffer;
 initPosition = 0;
}

代码示例来源:origin: apache/kafka

/**
 * Check if the given ByteBuffer capacity
 * @param existingBuffer ByteBuffer capacity to check
 * @param newLength new length for the ByteBuffer.
 * returns ByteBuffer
 */
public static ByteBuffer ensureCapacity(ByteBuffer existingBuffer, int newLength) {
  if (newLength > existingBuffer.capacity()) {
    ByteBuffer newBuffer = ByteBuffer.allocate(newLength);
    existingBuffer.flip();
    newBuffer.put(existingBuffer);
    return newBuffer;
  }
  return existingBuffer;
}

代码示例来源:origin: apache/avro

@Override public ByteBuffer compute(ByteBuffer data) {
 crc32.reset();
 crc32.update(data.array(), data.position(), data.remaining());
 ByteBuffer result = ByteBuffer.allocate(size());
 result.putInt((int)crc32.getValue());
 result.flip();
 return result;
}

代码示例来源:origin: bumptech/glide

@Override
 public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {
  messageDigest.update(ID_BYTES);

  byte[] degreesData = ByteBuffer.allocate(4).putInt(degreesToRotate).array();
  messageDigest.update(degreesData);
 }
}

代码示例来源:origin: lettuce-io/lettuce-core

private byte[] maxValue(Range<? extends V> range) {
  Boundary<? extends V> upper = range.getUpper();
  if (upper.getValue() == null) {
    return PLUS_BYTES;
  }
  ByteBuffer encoded = codec.encodeValue(upper.getValue());
  ByteBuffer allocated = ByteBuffer.allocate(encoded.remaining() + 1);
  allocated.put(upper.isIncluding() ? (byte) '[' : (byte) '(').put(encoded);
  return allocated.array();
}

代码示例来源:origin: apache/incubator-druid

@Override
public byte[] getCacheKey()
{
 byte[] fieldNameBytes = StringUtils.toUtf8WithNullToEmpty(fieldName);
 byte[] expressionBytes = StringUtils.toUtf8WithNullToEmpty(expression);
 return ByteBuffer.allocate(2 + fieldNameBytes.length + expressionBytes.length)
          .put(AggregatorUtil.DOUBLE_MAX_CACHE_TYPE_ID)
          .put(fieldNameBytes)
          .put(AggregatorUtil.STRING_SEPARATOR)
          .put(expressionBytes)
          .array();
}

代码示例来源:origin: Tencent/tinker

public DexDataBuffer() {
  this.data = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE);
  this.data.order(ByteOrder.LITTLE_ENDIAN);
  this.dataBound = this.data.position();
  this.data.limit(this.data.capacity());
  this.isResizeAllowed = true;
}

代码示例来源:origin: apache/incubator-dubbo

@Override
public ChannelBuffer copy(int index, int length) {
  ByteBuffer src;
  try {
    src = (ByteBuffer) buffer.duplicate().position(index).limit(index + length);
  } catch (IllegalArgumentException e) {
    throw new IndexOutOfBoundsException();
  }
  ByteBuffer dst = buffer.isDirect()
      ? ByteBuffer.allocateDirect(length)
      : ByteBuffer.allocate(length);
  dst.put(src);
  dst.clear();
  return new ByteBufferBackedChannelBuffer(dst);
}

代码示例来源:origin: netty/netty

/**
 * Create a copy of {@code value} into this instance using the encoding type of {@code charset}.
 * The copy will start at index {@code start} and copy {@code length} bytes.
 */
public AsciiString(CharSequence value, Charset charset, int start, int length) {
  CharBuffer cbuf = CharBuffer.wrap(value, start, start + length);
  CharsetEncoder encoder = CharsetUtil.encoder(charset);
  ByteBuffer nativeBuffer = ByteBuffer.allocate((int) (encoder.maxBytesPerChar() * length));
  encoder.encode(cbuf, nativeBuffer, true);
  final int offset = nativeBuffer.arrayOffset();
  this.value = Arrays.copyOfRange(nativeBuffer.array(), offset, offset + nativeBuffer.position());
  this.offset = 0;
  this.length = this.value.length;
}

代码示例来源:origin: google/guava

public void testFromByteArray_withTooLongArrayInputThrowsIllegalArgumentException() {
 byte[] buffer = MANY_VALUES_PAIRED_STATS.toByteArray();
 byte[] tooLongByteArray =
   ByteBuffer.allocate(buffer.length + 2)
     .order(ByteOrder.LITTLE_ENDIAN)
     .put(buffer)
     .putChar('.')
     .array();
 try {
  PairedStats.fromByteArray(tooLongByteArray);
  fail("Expected IllegalArgumentException");
 } catch (IllegalArgumentException expected) {
 }
}

代码示例来源:origin: neo4j/neo4j

private void writeHeader( long highId ) throws IOException
{
  ByteBuffer buffer = ByteBuffer.allocate( HEADER_SIZE );
  buffer.put( STICKY_GENERATOR ).putLong( highId ).flip();
  fileChannel.position( 0 );
  fileChannel.writeAll( buffer );
}

代码示例来源:origin: lettuce-io/lettuce-core

BulkStringSupport(ByteBuffer message) {
    if (message != null) {
      // need to copy the buffer to prevent buffer lifecycle mismatch
      this.message = ByteBuffer.allocate(message.remaining());
      this.message.put(message);
      this.message.rewind();
    } else {
      this.message = null;
    }
  }
}

代码示例来源:origin: apache/incubator-druid

@Override
public Object get(ByteBuffer buf, int position)
{
 final int size = HyperLogLogCollector.getLatestNumBytesForDenseStorage();
 ByteBuffer dataCopyBuffer = ByteBuffer.allocate(size);
 ByteBuffer mutationBuffer = buf.duplicate();
 mutationBuffer.position(position);
 mutationBuffer.limit(position + size);
 dataCopyBuffer.put(mutationBuffer);
 dataCopyBuffer.rewind();
 return HyperLogLogCollector.makeCollector(dataCopyBuffer);
}

代码示例来源:origin: apache/kafka

@Test
public void testParseUnknownVersion() {
  ByteBuffer buffer = ByteBuffer.allocate(32);
  buffer.putShort((short) 5);
  buffer.putShort(ControlRecordType.ABORT.type);
  buffer.putInt(23432); // some field added in version 5
  buffer.flip();
  ControlRecordType type = ControlRecordType.parse(buffer);
  assertEquals(ControlRecordType.ABORT, type);
}

代码示例来源:origin: google/guava

@Override
public HashCode hashLong(long input) {
 return hashBytes(ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).putLong(input).array());
}

代码示例来源:origin: apache/kafka

private void testWriteByteBuffer(ByteBuffer input) throws IOException {
  long value = 234239230L;
  input.putLong(value);
  input.flip();
  ByteBufferOutputStream output = new ByteBufferOutputStream(ByteBuffer.allocate(32));
  output.write(input);
  assertEquals(8, input.position());
  assertEquals(8, output.position());
  assertEquals(value, output.buffer().getLong(0));
  output.close();
}

代码示例来源:origin: apache/kafka

@Test
public void testUpdateInt() {
  final int value = 1000;
  final ByteBuffer buffer = ByteBuffer.allocate(4);
  buffer.putInt(value);
  Checksum crc1 = Crc32C.create();
  Checksum crc2 = Crc32C.create();
  Checksums.updateInt(crc1, value);
  crc2.update(buffer.array(), buffer.arrayOffset(), 4);
  assertEquals("Crc values should be the same", crc1.getValue(), crc2.getValue());
}

相关文章