카테고리 없음
[Java] ByteBuffer 예제 및 사용법
2021. 10. 14. 22:59반응형
ByteBuffer.warp(byte);
wrap(byte[] array)
버퍼 안을 byte array로 랩핑한다.
(Wraps a byte array into a buffer.)
wrap(byte[] array, int offset, int length)
버퍼 안을 byte array로 랩핑한다.
(Wraps a byte array into a buffer.)
예제1. ByteBuffer get, put, allocate, mark, reset 예제
더보기
아래의 소스코드는 아래의 게시글의 소스코드를, 제가 이해하기 쉽게 변형/추가하여 작성하였습니다.
https://jink1982.tistory.com/198
import java.nio.ByteBuffer;
public class ByteBufferExam {
public static void main(String[] args) {
ByteBuffer buf = ByteBuffer.allocate(10);
buf.mark(); // 나중에 찾아 오기 위해 현재 위치를 기억해 둔다. (현재 위치는 0 )
//순차적으로 데이터 넣기 -> 데이터를 넣을 때 마다 position이 바뀐다.
buf.put((byte)20);
System.out.println("put result (" + 20 + ") -> position[" + buf.position() +"]");
buf.put((byte)21);
System.out.println("put result (" + 21 + ") -> position[" + buf.position() +"]");
buf.put((byte)22);
System.out.println("put result (" + 22 + ") -> position[" + buf.position() +"]");
//mark 해 두었던 위치로 이동
buf.reset();
System.out.println("put reset -> position[" + buf.position() +"]");
System.out.println("");
System.out.println("데이터 들어간 결과 확인");
//데이터를 get 할 때 마다 position이 바뀐다.
for( int i = 0 ; i < 5 ; i++ ) {
System.out.println("position[" + buf.position() +"] value["+ buf.get() + "]");
}
//지정한 위치에 데이터에 넣기
buf.put(2, (byte)22);
buf.put(3, (byte)23);
buf.put(4, (byte)24);
System.out.println("");
System.out.println("데이터 확인");
for( int i = 0 ; i < 5 ; i++ ) {
System.out.println("position[" + i +"] value["+ buf.get(i) + "]");
}
System.out.println("다시한번 buf.get(0) Get: " + buf.get(0));
}
}
출력결과
put result (20) -> position[1] put result (21) -> position[2] put result (22) -> position[3] put reset -> position[0] 데이터 들어간 결과 확인 position[0] value[20] position[1] value[21] position[2] value[22] position[3] value[0] position[4] value[0] 데이터 확인 position[0] value[20] position[1] value[21] position[2] value[22] position[3] value[23] position[4] value[24] 다시한번 Get: 20 |
예제2. ByteBuffer에 있는 내용 출력하기
더보기
< 소스코드 >
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws UnknownHostException {
InetAddress a;
byte[] bytes = {23, 24, 25, 26};
InetAddress serverAddress = InetAddress.getByAddress(bytes);
ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
if (serverAddress instanceof Inet4Address) {
System.out.println("This is a IPv4 !!!");
}
buffer.put(serverAddress.getAddress());
buffer.flip();
byte[] array = new byte[buffer.remaining()];
buffer.get(array);
System.out.println("starts");
for (int i = 0; i < array.length; i++) {
System.out.printf("%s, ", array[i]);
}
}
}
< 출력화면 >
This is a IPv4 !!! starts 23, 24, 25, 26, |
반응형