java.nio.ByteBuffer类的使用及代码示例

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

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

ByteBuffer介绍

[英]A buffer for bytes.

A byte buffer can be created in either one of the following ways:

  • #allocate(int) a new byte array and create a buffer based on it;
  • #allocateDirect(int) a memory block and create a direct buffer based on it;
  • #wrap(byte[]) an existing byte array to create a new buffer.
    [中]字节的缓冲区。
    字节缓冲区可以通过以下任一方式创建:
    *#分配(int)一个新的字节数组并基于它创建一个缓冲区;
    *#分配direct(int)内存块并基于它创建直接缓冲区;
    *#包装(字节[])现有字节数组以创建新缓冲区。

代码示例

代码示例来源:origin: spring-projects/spring-framework

private Object convertToByteBuffer(@Nullable Object source, TypeDescriptor sourceType) {
  byte[] bytes = (byte[]) (source instanceof byte[] ? source :
      this.conversionService.convert(source, sourceType, BYTE_ARRAY_TYPE));
  if (bytes == null) {
    return ByteBuffer.wrap(new byte[0]);
  }
  ByteBuffer byteBuffer = ByteBuffer.allocate(bytes.length);
  byteBuffer.put(bytes);
  // Extra cast necessary for compiling on JDK 9 plus running on JDK 8, since
  // otherwise the overridden ByteBuffer-returning rewind method would be chosen
  // which isn't available on JDK 8.
  return ((Buffer) byteBuffer).rewind();
}

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

@Override
public Hasher putBytes(ByteBuffer b) {
 if (b.hasArray()) {
  putBytes(b.array(), b.arrayOffset() + b.position(), b.remaining());
  b.position(b.limit());
 } else {
  for (int remaining = b.remaining(); remaining > 0; remaining--) {
   putByte(b.get());
  }
 }
 return this;
}

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

private void expandBuffer(int remainingRequired) {
  int expandSize = Math.max((int) (buffer.limit() * REALLOCATION_FACTOR), buffer.position() + remainingRequired);
  ByteBuffer temp = ByteBuffer.allocate(expandSize);
  int limit = limit();
  buffer.flip();
  temp.put(buffer);
  buffer.limit(limit);
  // reset the old buffer's position so that the partial data in the new buffer cannot be mistakenly consumed
  // we should ideally only do this for the original buffer, but the additional complexity doesn't seem worth it
  buffer.position(initialPosition);
  buffer = temp;
}

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

@Override
protected void processRemaining(ByteBuffer buffer) {
 b += buffer.remaining();
 for (int i = 0; buffer.hasRemaining(); i += 8) {
  finalM ^= (buffer.get() & 0xFFL) << i;
 }
}

代码示例来源: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: netty/netty

/**
 * Initialize an instance based upon the underlying storage from {@code value}.
 * There is a potential to share the underlying array storage if {@link ByteBuffer#hasArray()} is {@code true}.
 * if {@code copy} is {@code true} a copy will be made of the memory.
 * if {@code copy} is {@code false} the underlying storage will be shared, if possible.
 */
public AsciiString(ByteBuffer value, boolean copy) {
  this(value, value.position(), value.remaining(), copy);
}

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

@Override
public void setBytes(int index, ByteBuffer src) {
  ByteBuffer data = buffer.duplicate();
  data.limit(index + src.remaining()).position(index);
  data.put(src);
}

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

public static ChannelBuffer wrappedBuffer(ByteBuffer buffer) {
  if (!buffer.hasRemaining()) {
    return EMPTY_BUFFER;
  }
  if (buffer.hasArray()) {
    return wrappedBuffer(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining());
  } else {
    return new ByteBufferBackedChannelBuffer(buffer);
  }
}

代码示例来源:origin: spring-projects/spring-framework

private ByteBuffer assembleChunksAndReset() {
  ByteBuffer result;
  if (this.chunks.size() == 1) {
    result = this.chunks.remove();
  }
  else {
    result = ByteBuffer.allocate(getBufferSize());
    for (ByteBuffer partial : this.chunks) {
      result.put(partial);
    }
    result.flip();
  }
  this.chunks.clear();
  this.expectedContentLength = null;
  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: google/guava

/**
  * Copy as much of the byte buffer into the output array as possible, returning the (positive)
  * number of characters copied.
  */
 private int drain(byte[] b, int off, int len) {
  int remaining = Math.min(len, byteBuffer.remaining());
  byteBuffer.get(b, off, remaining);
  return remaining;
 }
}

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

@Override
public HashCode hashInt(int input) {
 return hashBytes(ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(input).array());
}

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

public void testFromByteArrayWithTooShortArrayInputThrowsIllegalArgumentException() {
 byte[] buffer = MANY_VALUES_STATS_VARARGS.toByteArray();
 byte[] tooShortByteArray =
   ByteBuffer.allocate(buffer.length - 1)
     .order(ByteOrder.LITTLE_ENDIAN)
     .put(buffer, 0, Stats.BYTES - 1)
     .array();
 try {
  Stats.fromByteArray(tooShortByteArray);
  fail("Expected IllegalArgumentException");
 } catch (IllegalArgumentException expected) {
 }
}

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

@Override
public final HashCode hash() {
 munch();
 buffer.flip();
 if (buffer.remaining() > 0) {
  processRemaining(buffer);
  buffer.position(buffer.limit());
 }
 return makeHash();
}

代码示例来源:origin: spring-projects/spring-framework

private DataBuffer toDataBuffer(String body, Charset charset) {
  byte[] bytes = body.getBytes(charset);
  ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
  return this.bufferFactory.wrap(byteBuffer);
}

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

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

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

/** Returns a {@link HashCode} for a sequence of longs, in big-endian order. */
private static HashCode toHashCode(long... longs) {
 ByteBuffer bb = ByteBuffer.wrap(new byte[longs.length * 8]).order(ByteOrder.LITTLE_ENDIAN);
 for (long x : longs) {
  bb.putLong(x);
 }
 return HashCode.fromBytes(bb.array());
}

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

/**
 * This is invoked for the last bytes of the input, which are not enough to fill a whole chunk.
 * The passed {@code ByteBuffer} is guaranteed to be non-empty.
 *
 * <p>This implementation simply pads with zeros and delegates to {@link #process(ByteBuffer)}.
 */
protected void processRemaining(ByteBuffer bb) {
 bb.position(bb.limit()); // move at the end
 bb.limit(chunkSize + 7); // get ready to pad with longs
 while (bb.position() < chunkSize) {
  bb.putLong(0);
 }
 bb.limit(chunkSize);
 bb.flip();
 process(bb);
}

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

@Override
public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) {
  if (dst instanceof ByteBufferBackedChannelBuffer) {
    ByteBufferBackedChannelBuffer bbdst = (ByteBufferBackedChannelBuffer) dst;
    ByteBuffer data = bbdst.buffer.duplicate();
    data.limit(dstIndex + length).position(dstIndex);
    getBytes(index, data);
  } else if (buffer.hasArray()) {
    dst.setBytes(dstIndex, buffer.array(), index + buffer.arrayOffset(), length);
  } else {
    dst.setBytes(dstIndex, this, index, length);
  }
}

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

/**
 * Gets a byte array representation of this instance.
 *
 * <p><b>Note:</b> No guarantees are made regarding stability of the representation between
 * versions.
 */
public byte[] toByteArray() {
 ByteBuffer buffer = ByteBuffer.allocate(BYTES).order(ByteOrder.LITTLE_ENDIAN);
 xStats.writeTo(buffer);
 yStats.writeTo(buffer);
 buffer.putDouble(sumOfProductsOfDeltas);
 return buffer.array();
}

相关文章

微信公众号

最新文章

更多