Метод ByteBuffer getInt () в Java с примерами
Метод getInt () класса java.nio.ByteBuffer используется для чтения следующих четырех байтов в текущей позиции этого буфера, компоновки их в значение int в соответствии с текущим порядком байтов, а затем увеличивает позицию на четыре.
Синтаксис:
общедоступный абстрактный int getInt ()
Возвращаемое значение: этот метод возвращает значение типа int в текущей позиции буфера.
Броски: этот метод вызывает исключение BufferUnderflowException - если в этом буфере осталось менее четырех байтов.
Ниже приведены примеры, иллюстрирующие метод getInt ():
Примеры 1:
Examples 2:
// Java program to demonstrate// getInt() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 8; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int value in the bytebuffer bb.asIntBuffer() .put(10) .put(20); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println("Original ByteBuffer: "); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getInt() + " "); // rewind the Bytebuffer bb.rewind(); // Reads the Int at this buffer"s current position // using getInt() method int value = bb.getInt(); // print the int value System.out.println("
Byte Value: " + value); // Reads the int at this buffer"s next position // using getInt() method int value1 = bb.getInt(); // print the int value System.out.println("Next Byte Value: " + value1); // Reads the int at this buffer"s next position // using getInt() method int value2 = bb.getInt(); } catch (BufferUnderflowException e) { System.out.println("
there are fewer than " + "four bytes remaining in this buffer"); System.out.println("Exception Thrown : " + e); } }} |
Original ByteBuffer: 10 20 Byte Value: 10 Next Byte Value: 20 there are fewer than four bytes remaining in this buffer Exception Thrown : java.nio.BufferUnderflowException
Ссылка: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#getInt–
Метод getInt (int index) класса ByteBuffer используется для чтения четырех байтов по заданному индексу, составляя их в значение типа int в соответствии с текущим порядком байтов.
Синтаксис:
общедоступный абстрактный int getInt (индекс int)
Параметры: этот метод принимает индекс (индекс, из которого будет считываться байт) в качестве параметра.
Возвращаемое значение: этот метод возвращает значение типа int по заданному индексу.
Исключение: этот метод вызывает исключение IndexOutOfBoundsException . Если индекс отрицательный или не меньше предела буфера, выдается исключение.
Ниже приведены примеры, иллюстрирующие метод getInt (int index) :
Examples 1:
// Java program to demonstrate// getInt() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 8; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int value in the bytebuffer bb.asIntBuffer() .put(10) .put(20); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println("Original ByteBuffer: "); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getInt() + " "); // rewind the Bytebuffer bb.rewind(); // Reads the Int at this buffer"s current position // using getInt() method int value = bb.getInt(0); // print the int value System.out.println("
Byte Value: " + value); // Reads the int at this buffer"s next position // using getInt() method int value1 = bb.getInt(4); // print the int value System.out.println("Next Byte Value: " + value1); } catch (IndexOutOfBoundsException e) { System.out.println("
index is negative or smaller " + "than the buffer"s limit, minus seven"); System.out.println("Exception Thrown : " + e); } }} |
Original ByteBuffer: 10 20 Byte Value: 10 Next Byte Value: 20
Examples 2:
// Java program to demonstrate// getInt() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 8; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(capacity); // putting the int value in the bytebuffer bb.asIntBuffer() .put(10) .put(20); // rewind the Bytebuffer bb.rewind(); // print the ByteBuffer System.out.println("Original ByteBuffer: "); for (int i = 1; i <= capacity / 4; i++) System.out.print(bb.getInt() + " "); // rewind the Bytebuffer bb.rewind(); // Reads the Int at this buffer"s current position // using getInt() method int value = bb.getInt(0); // print the int value System.out.println("
Byte Value: " + value); // Reads the int at this buffer"s next position // using getInt() method int value1 = bb.getInt(7); // print the int value System.out.println("Next Byte Value: " + value1); } catch (IndexOutOfBoundsException e) { System.out.println("
index is negative or smaller" + " than the buffer"s limit, minus seven"); System.out.println("Exception Thrown : " + e); } }} |
Original ByteBuffer: 10 20 Byte Value: 10 index is negative or smaller than the buffer"s limit, minus seven Exception Thrown : java.lang.IndexOutOfBoundsException
Ссылка: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#getInt-int-
Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .