Java NIO-파이프

Java에서 NIO 파이프는 두 스레드간에 데이터를 쓰고 읽는 데 사용되는 구성 요소로, 파이프는 주로 데이터 전파를 담당하는 두 채널로 구성됩니다.

두 개의 구성 채널 중 하나는 주로 데이터 쓰기를위한 Sink 채널이라고하고 다른 하나는 Sink 채널에서 데이터를 읽는 것이 주 목적인 Source 채널입니다.

데이터 동기화는 데이터가 파이프에 기록되는 순서와 동일한 순서로 읽혀 져야하기 때문에 데이터 쓰기 및 읽기 동안 순서대로 유지됩니다.

파이프에서 데이터의 단방향 흐름이라는 점에 유의해야합니다. 즉, 데이터는 싱크 채널에만 기록되고 소스 채널에서만 읽을 수 있습니다.

Java에서 NIO 파이프는 주로 세 가지 메서드가있는 추상 클래스로 정의되며 그 중 두 가지는 추상입니다.

파이프 클래스의 방법

  • open() −이 메서드는 Pipe의 인스턴스를 가져 오거나이 메서드를 호출하여 파이프가 생성되었다고 말할 수 있습니다.

  • sink() −이 메서드는 write 메서드를 호출하여 데이터를 쓰는 데 사용되는 Pipe의 싱크 채널을 반환합니다.

  • source() −이 메서드는 read 메서드를 호출하여 데이터를 읽는 데 사용되는 Pipe의 소스 채널을 반환합니다.

다음 예제는 Java NIO 파이프의 구현을 보여줍니다.

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.Pipe;

public class PipeDemo {
   public static void main(String[] args) throws IOException {
      //An instance of Pipe is created
      Pipe pipe = Pipe.open();
      // gets the pipe's sink channel
      Pipe.SinkChannel skChannel = pipe.sink();
      String testData = "Test Data to Check java NIO Channels Pipe.";
      ByteBuffer buffer = ByteBuffer.allocate(512);
      buffer.clear();
      buffer.put(testData.getBytes());
      buffer.flip();
      //write data into sink channel.
      while(buffer.hasRemaining()) {
         skChannel.write(buffer);
      }
      //gets  pipe's source channel
      Pipe.SourceChannel sourceChannel = pipe.source();
      buffer = ByteBuffer.allocate(512);
      //write data into console     
      while(sourceChannel.read(buffer) > 0){
         //limit is set to current position and position is set to zero
         buffer.flip();
         while(buffer.hasRemaining()){
            char ch = (char) buffer.get();
            System.out.print(ch);
         }
         //position is set to zero and limit is set to capacity to clear the buffer.
         buffer.clear();
      }
   }
}

산출

Test Data to Check java NIO Channels Pipe.

텍스트 파일이 있다고 가정합니다. c:/test.txt, 다음과 같은 내용이 있습니다. 이 파일은 예제 프로그램의 입력으로 사용됩니다.