5. The Pipe (Pipe)

A Java NIO pipe is a one-way data connection between two threads. Pipe has a source channel and a sink channel. Data will be written to the sink channel and read from the source channel.

5.1 Writing Data to a Pipe

	public void test01(a) throws IOException {
		String str = "Test data";

		// Create a pipe
		Pipe pipe = Pipe.open();

		// Write input to the pipe
		Pipe.SinkChannel sinkChannel = pipe.sink();

		// Write data through SinkChannel's write() method
		ByteBuffer buf = ByteBuffer.allocate(1024);
		buf.clear();
		buf.put(str.getBytes());

		while(buf.hasRemaining()) { sinkChannel.write(buf); }}Copy the code

5.2 Reading Data to Pipes

	public void test02(a) throws IOException {
		// Create a pipe
		Pipe pipe = Pipe.open();

		// Read data from the pipe
		Pipe.SourceChannel sourceChannel = pipe.source();

		// Call SourceChannel's read() method to fetch data
		ByteBuffer buf = ByteBuffer.allocate(1024);
		sourceChannel.read(buf);
	}
Copy the code