본문 바로가기

개발 이야기

JAVA ByteBuffer 궁금점 정리

320x100

ByteBuffer 정의

ByteBuffer는 Java에서 바이트 배열에 대한 뷰를 제공하며, 바이트 배열의 데이터를 효과적으로 읽고 쓸 수 있는 메서드를 제공합니다. ByteBuffer는 주로 다음과 같은 상황에서 사용됩니다:

  1. 파일 I/O: ByteBuffer는 파일에서 데이터를 읽거나 파일에 데이터를 쓸 때 사용됩니다. 이 경우 FileChannel과 함께 사용되며, ByteBuffer가 파일로부터 데이터를 읽어오거나 파일에 데이터를 쓰게 됩니다.

  2. 소켓 네트워킹: 소켓을 통해 네트워크로부터 데이터를 받아오거나 네트워크로 데이터를 보낼 때도 ByteBuffer가 사용됩니다. 이 경우 SocketChannel과 함께 사용되며, ByteBuffer가 소켓으로부터 데이터를 읽어오거나 소켓에 데이터를 쓰게 됩니다.

  3. 바이너리 데이터 처리: ByteBuffer는 바이너리 형태의 원시데이터(raw data) 처리에 유용합니다. 예로 이미지, 오디오 등의 미디어 파일 또는 직렬화된 객체 등을 처리할 때 많이 활용됩니다.

아래 코드 예제는 파일 I/O에서의 ByteBuffer 사용법을 보여줍니다:

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
    public static void main(String[] args) {
        try {
            RandomAccessFile aFile = new RandomAccessFile("test.txt", "rw");
            FileChannel inChannel = aFile.getChannel();

            // create buffer with capacity of 48 bytes
            ByteBuffer buf = ByteBuffer.allocate(48);

            int bytesRead = inChannel.read(buf); // read into buffer.
            while (bytesRead != -1) {

                buf.flip();  // make buffer ready for read

                while (buf.hasRemaining()) {
                    System.out.print((char) buf.get()); // read 1 byte at a time
                }

                buf.clear(); // make buffer ready for writing
                bytesRead = inChannel.read(buf);
            }
            aFile.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
    }
}

위 코드는 "test.txt"라는 이름의 파일에서 문자들을 읽어와 한 문자씩 출력하는 과정입니다. ByteBufferFileChannel을 함께 활용하여 효율적인 파일 입출력 작업을 수행하고 있습니다.

ByteBuffer 사용용도

ByteBuffer는 Java에서 바이트 배열에 대한 뷰를 제공하며, 바이트 배열의 데이터를 효과적으로 읽고 쓸 수 있는 메서드를 제공합니다. ByteBuffer는 주로 다음과 같은 상황에서 사용됩니다:

  1. 파일 I/O: ByteBuffer는 파일에서 데이터를 읽거나 파일에 데이터를 쓸 때 사용됩니다. 이 경우 FileChannel과 함께 사용되며, ByteBuffer가 파일로부터 데이터를 읽어오거나 파일에 데이터를 쓰게 됩니다.

  2. 소켓 네트워킹: 소켓을 통해 네트워크로부터 데이터를 받아오거나 네트워크로 데이터를 보낼 때도 ByteBuffer가 사용됩니다. 이 경우 SocketChannel과 함께 사용되며, ByteBuffer가 소켓으로부터 데이터를 읽어오거나 소켓에 데이터를 쓰게 됩니다.

  3. 바이너리 데이터 처리: ByteBuffer는 바이너리 형태의 원시데이터(raw data) 처리에 유용합니다. 예로 이미지, 오디오 등의 미디어 파일 또는 직렬화된 객체 등을 처리할 때 많이 활용됩니다.

아래 코드 예제는 파일 I/O에서의 ByteBuffer 사용법을 보여줍니다:

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
    public static void main(String[] args) {
        try {
            RandomAccessFile aFile = new RandomAccessFile("test.txt", "rw");
            FileChannel inChannel = aFile.getChannel();

            // create buffer with capacity of 48 bytes
            ByteBuffer buf = ByteBuffer.allocate(48);

            int bytesRead = inChannel.read(buf); // read into buffer.
            while (bytesRead != -1) {

                buf.flip();  // make buffer ready for read

                while (buf.hasRemaining()) {
                    System.out.print((char) buf.get()); // read 1 byte at a time
                }

                buf.clear(); // make buffer ready for writing
                bytesRead = inChannel.read(buf);
            }
            aFile.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
    }
}

위 코드는 "test.txt"라는 이름의 파일에서 문자들을 읽어와 한 문자씩 출력하는 과정입니다. ByteBufferFileChannel을 함께 활용하여 효율적인 파일 입출력 작업을 수행하고 있습니다.

반응형