當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Buffer remaining()用法及代碼示例


java.nio.Buffer類的remaining()方法用於返回當前位置和限製之間的元素數。

用法:

public final int remaining()

返回值:此方法返回此緩衝區中剩餘的元素數。


下麵是說明remaining()方法的示例:

範例1:

// Java program to demonstrate 
// remaining() method 
  
import java.nio.*; 
import java.util.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Declare and initialize the byte array 
        byte[] bb = { 10, 20, 30 }; 
  
        // wrap the byte array into ByteBuffer 
        // using wrap() method 
        ByteBuffer byteBuffer = ByteBuffer.wrap(bb); 
  
        // Typecast ByteBuffer to Buffer 
        Buffer buffer = (Buffer)byteBuffer; 
  
        // get the number of element present in the Buffer 
        // using remaining() method 
        int element = buffer.remaining(); 
  
        // print the buffer 
        System.out.println("Remaining element in buffer:"
                           + element); 
    } 
}
輸出:
Remaining element in buffer:3

範例2:

// Java program to demonstrate 
// remaining() method 
  
import java.nio.*; 
import java.util.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // defining and allocating ByteBuffer 
        // using allocate() method 
        ByteBuffer byteBuffer = ByteBuffer.allocate(7); 
  
        // put byte value in byteBuffer 
        // using put() method 
        byteBuffer.put((byte)20); // 1 byte space required 
        byteBuffer.put((byte)30); // 1 byte space required 
        byteBuffer.putInt(40); // 4 byte space required 
  
        // Typecast ByteBuffer to Buffer 
        Buffer buffer = (Buffer)byteBuffer; 
  
        // get the number of element present in the Buffer 
        // using remaining() method 
        int element = buffer.remaining(); 
  
        // print the buffer 
        System.out.println("Remaining element in buffer:"
                           + element); 
    } 
}
輸出:
Remaining element in buffer:1

參考: https://docs.oracle.com/javase/9/docs/api/java/nio/Buffer.html#remaining-



相關用法


注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 Buffer remaining() methods in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。