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

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

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

Buffer介绍

[英]A buffer is a list of elements of a specific primitive type.

A buffer can be described by the following properties:

  • Capacity: the number of elements a buffer can hold. Capacity may not be negative and never changes.
  • Position: a cursor of this buffer. Elements are read or written at the position if you do not specify an index explicitly. Position may not be negative and not greater than the limit.
  • Limit: controls the scope of accessible elements. You can only read or write elements from index zero to limit - 1. Accessing elements out of the scope will cause an exception. Limit may not be negative and not greater than capacity.
  • Mark: used to remember the current position, so that you can reset the position later. Mark may not be negative and no greater than position.
  • A buffer can be read-only or read-write. Trying to modify the elements of a read-only buffer will cause a ReadOnlyBufferException, while changing the position, limit and mark of a read-only buffer is OK.
  • A buffer can be direct or indirect. A direct buffer will try its best to take advantage of native memory APIs and it may not stay in the Java heap, thus it is not affected by garbage collection.

Buffers are not thread-safe. If concurrent access to a buffer instance is required, then the callers are responsible to take care of the synchronization issues.
[中]缓冲区是特定基元类型的元素列表。
缓冲区可由以下属性描述:
*容量:缓冲区可以容纳的元素数。容量可能不会为负,也不会发生变化。
*位置:此缓冲区的光标。如果未明确指定索引,则在该位置读取或写入元素。位置不得为负值且不得大于极限值。
*限制:控制可访问元素的范围。只能读取或写入从索引0到limit - 1的元素。访问范围外的元素将导致异常。限制不能为负值,也不能大于容量。
*标记:用于记住当前位置,以便以后可以重置位置。标记不得为负数且不得大于位置。
*缓冲区可以是只读的或读写的。尝试修改只读缓冲区的元素将导致ReadOnlyBufferException,而更改只读缓冲区的位置、限制和标记是可以的。
*缓冲区可以是直接的,也可以是间接的。直接缓冲区将尽最大努力利用本机内存API,它可能不会留在Java堆中,因此不会受到垃圾收集的影响。
缓冲区不是线程安全的。如果需要并发访问缓冲区实例,则调用方负责处理同步问题。

代码示例

代码示例来源:origin: stackoverflow.com

private byte[] toBytes(char[] chars) {
  CharBuffer charBuffer = CharBuffer.wrap(chars);
  ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
  byte[] bytes = Arrays.copyOfRange(byteBuffer.array(),
      byteBuffer.position(), byteBuffer.limit());
  Arrays.fill(charBuffer.array(), '\u0000'); // clear sensitive data
  Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
  return bytes;
}

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

/** Returns the number of elements between the limit and capacity. */
private static int availableCapacity(Buffer buffer) {
 return buffer.capacity() - buffer.limit();
}

代码示例来源:origin: org.jsoup/jsoup

public String body() {
  prepareByteData();
  // charset gets set from header on execute, and from meta-equiv on parse. parse may not have happened yet
  String body;
  if (charset == null)
    body = Charset.forName(DataUtil.defaultCharset).decode(byteData).toString();
  else
    body = Charset.forName(charset).decode(byteData).toString();
  ((Buffer)byteData).rewind(); // cast to avoid covariant return type change in jdk9
  return body;
}

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

private void write(ByteBuffer source) {
  int length = source.remaining();
  ByteBuffer tmp = this.byteBuffer.duplicate();
  int limit = this.writePosition + source.remaining();
  ((Buffer) tmp).clear().position(this.writePosition).limit(limit);
  tmp.put(source);
  this.writePosition += length;
}

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

@Override
public ByteBuffer asByteBuffer(int index, int length) {
  checkIndex(index, length);
  ByteBuffer duplicate = this.byteBuffer.duplicate();
  // Explicit access via Buffer base type for compatibility
  // with covariant return type on JDK 9's ByteBuffer...
  Buffer buffer = duplicate;
  buffer.position(index);
  buffer.limit(index + length);
  return duplicate.slice();
}

代码示例来源:origin: stackoverflow.com

int blockSize = 32 * 1024;
ByteBuffer bb = ByteBuffer.allocateDirect(blockSize);
FileChannel out = new FileOutputStream("deleteme.dat").getChannel();
for (int i = 0; i < (1024 << 20); i += blockSize) {
  bb.clear();
  while (bb.remaining() > 0)
    if (out.write(bb) < 1) throw new AssertionError();
}
out.close();

long start = System.nanoTime();
FileChannel in = new FileInputStream("deleteme.dat").getChannel();
MappedByteBuffer map = in.map(FileChannel.MapMode.READ_ONLY, 0, in.size());
in.close();
long end = System.nanoTime();
System.out.printf("Mapped file at a rate of %.1f MB/s%n",
    1024 * 1e9 / (end - start));

代码示例来源:origin: stackoverflow.com

public static void main(String... args) throws IOException {
  for (int i = 512; i <= 2 * 1024 * 1024; i *= 2)
    readWrite(i);
}

private static void readWrite(int blockSize) throws IOException {
  ByteBuffer bb = ByteBuffer.allocateDirect(blockSize);
  long start = System.nanoTime();
  FileChannel out = new FileOutputStream("deleteme.dat").getChannel();
  for (int i = 0; i < (1024 << 20); i += blockSize) {
    bb.clear();
    while (bb.remaining() > 0)
      if (out.write(bb) < 1) throw new AssertionError();
  }
  out.close();
  long mid = System.nanoTime();
  FileChannel in = new FileInputStream("deleteme.dat").getChannel();
  for (int i = 0; i < (1024 << 20); i += blockSize) {
    bb.clear();
    while (bb.remaining() > 0)
      if (in.read(bb) < 1) throw new AssertionError();
  }
  in.close();
  long end = System.nanoTime();
  System.out.printf("With %.1f KB block size write speed %.1f MB/s, read speed %.1f MB/s%n",
      blockSize / 1024.0, 1024 * 1e9 / (mid - start), 1024 * 1e9 / (end - mid));
}

代码示例来源:origin: stackoverflow.com

try (FileChannel in = new FileInputStream(inFile).getChannel();
   FileChannel out = new FileOutputStream(outFile).getChannel()) 
{
  ByteBuffer buff = ByteBuffer.allocate(8192);

  int len;
  while ((len = in.read(buff)) > 0) { 
    buff.flip();
    out.write(buff);
    buff.clear();
  }
}

代码示例来源:origin: stackoverflow.com

// 4k buffer size.
static final int SIZE = 4 * 1024;
static byte[] buffer = new byte[SIZE];

// Fastest because a FileInputStream has an associated channel.
private static void ScanDataFile(Hunter p, FileInputStream f) throws FileNotFoundException, IOException {
  // Use a mapped and buffered stream for best speed.
  // See: http://nadeausoftware.com/articles/2008/02/java_tip_how_read_files_quickly
  final FileChannel ch = f.getChannel();
  long red = 0L;
  do {
    final long read = Math.min(Integer.MAX_VALUE, ch.size() - red);
    final MappedByteBuffer mb = ch.map(FileChannel.MapMode.READ_ONLY, red, read);
    int nGet;
    while (mb.hasRemaining() && p.ok()) {
      nGet = Math.min(mb.remaining(), SIZE);
      mb.get(buffer, 0, nGet);
      for (int i = 0; i < nGet && p.ok(); i++) {
        p.check(buffer[i]);
        //size += 1;
      }
    }
    red += read;
  } while (red < ch.size() && p.ok());
  // Finish off.
  p.close();
  ch.close();
  f.close();
}

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

FileOutputStream outputStream = new FileOutputStream(file);
int written = 0;
try {
  FileChannel localfileChannel = outputStream.getChannel();
  byte[] bytes = new byte[4096 * 4];
  ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
  int read = inputStream.read(bytes);
  while (read > 0) {
    byteBuffer.position(read).flip();
    written += localfileChannel.write(byteBuffer);
    checkSize(written);
    read = inputStream.read(bytes);
  localfileChannel.force(false);
} finally {
  outputStream.close();

代码示例来源:origin: smuyyh/BookReader

/**
 * Retrieves the content of a sent file and saves it to a temporary
 * file. The full path to the saved file is returned.
 */
private String saveTmpFile(ByteBuffer b, int offset, int len) {
  String path = "";
  if (len > 0) {
    try {
      TempFile tempFile = tempFileManager.createTempFile();
      ByteBuffer src = b.duplicate();
      FileChannel dest = new FileOutputStream(tempFile.getName())
          .getChannel();
      src.position(offset).limit(offset + len);
      dest.write(src.slice());
      path = tempFile.getName();
    } catch (Exception e) { // Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
  return path;
}

代码示例来源:origin: stackoverflow.com

int values = 1000000;
ByteBuffer buffer = ByteBuffer.allocateDirect(4 * values).order(ByteOrder.nativeOrder());

Random random = new Random(1);
long start = System.nanoTime();
for (int i = 0; i < values; i++)
  buffer.putInt(random.nextInt());
buffer.flip();
FileOutputStream fos = new FileOutputStream("/tmp/random.ints");
fos.getChannel().write(buffer);
fos.close();
long time = System.nanoTime() - start;
System.out.printf("Took %.3f seconds to generate&write %,d values%n", time / 1e9, values);

代码示例来源:origin: stackoverflow.com

final BufferedInputStream inputStream1 =
    new BufferedInputStream(
        new FileInputStream(
            new File(fileName1)),
        myBufferSize);
  if (first.size() != seconde.size()) {
    return false;
  ByteBuffer secondBuffer = ByteBuffer.allocateDirect(myBufferSize);
  int firstRead, secondRead;
  while (first.position() < first.size()) {
} finally {
  if (first != null) {
    first.close();
    seconde.close();
if (first.limit() != second.limit() || length > first.limit()) {
  return false;
first.rewind();
second.rewind();
for (int i = 0; i < length; i++) {
  if (first.get() != second.get()) {

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

FileOutputStream outputStream = new FileOutputStream(file);
FileChannel localfileChannel = outputStream.getChannel();
byte[] bytes = new byte[4096 * 4];
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
int written = 0;
while (read > 0) {
  byteBuffer.position(read).flip();
  written += localfileChannel.write(byteBuffer);
  checkSize(written);
  read = inputStream.read(bytes);
localfileChannel.force(false);
localfileChannel.close();
size = written;
if (definedSize > 0 && definedSize < size) {

代码示例来源:origin: stackoverflow.com

FileChannel fc = new FileInputStream(file).getChannel();
ByteBuffer bb = ByteBuffer.allocateDirect((int) fc.size());
while (bb.remaining() > 0) fc.read(bb);
fc.close();
bb.flip();
// choose the right endianness
ShortBuffer sb = bb.order(ByteOrder.LITTLE_ENDIAN).asShortBuffer();

代码示例来源:origin: stackoverflow.com

ByteBuffer myByteBuffer = ByteBuffer.allocate(20);
myByteBuffer.order(ByteOrder.LITTLE_ENDIAN);
FileChannel in = new FileInputStream("sample.bin").getChannel();
in.read(myByteBuffer);
myByteBuffer.flip();

ShortBuffer myShortBuffer = myByteBuffer.asShortBuffer();
myShortBuffer.get(payload);
System.out.println(Arrays.toString(payload));

代码示例来源:origin: stackoverflow.com

Charset utf8 = Charset.forName("UTF-8");
CharsetEncoder encoder = utf8.newEncoder();
char[] array = new char[1];
CharBuffer input = CharBuffer.wrap(array);
ByteBuffer output = ByteBuffer.allocate(10);
for (int reps = 0; reps < 10000; reps++) {
  for (array[0] = 0; array[0] < 10000; array[0]++) {
    output.clear();
    input.clear();
    encoder.encode(input, output, false);
    int len = output.position();
  }
}

代码示例来源:origin: stackoverflow.com

RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
FileChannel channel = randomAccessFile.getChannel();
MappedByteBuffer map = channel.map(MapMode.READ_WRITE, 0, imgIn.getRowBytes()*height);
imgIn.copyPixelsToBuffer(map);
map.position(0);
channel.close();
randomAccessFile.close();

代码示例来源:origin: stackoverflow.com

char[] c = "aaaaaaaaaa".toCharArray();
ByteBuffer bb = Charset.forName("UTF-8").encode(CharBuffer.wrap(c));
byte[] b = new byte[bb.remaining()];
bb.get(b);
System.out.println(Arrays.toString(b));

代码示例来源:origin: stackoverflow.com

CharsetDecoder cd = Charset.forName("UTF-8").newDecoder();
 ByteBuffer in = ByteBuffer.wrap(bytes);
 CharBuffer out = CharBuffer.allocate(1);
 int p = 0;
 while (in.hasRemaining()) {
   cd.decode(in, out, true);
   char c = out.array()[0];
   int nBytes = in.position() - p;
   p = in.position();
   out.position(0);
 }

相关文章