首页 > 代码库 > Java NIO Pipe
Java NIO Pipe
Java Nio
1 | Java NIO Tutorial |
2 | Java NIO Overview |
3 | Java NIO Channel |
4 | Java NIO Buffer |
5 | Java NIO Scatter / Gather |
6 | Java NIO Channel to Channel Transfers |
7 | Java NIO Selector |
8 | Java NIO FileChannel |
9 | Java NIO SocketChannel |
10 | Java NIO ServerSocketChannel |
11 | Java NIO DatagramChannel |
12 | Java NIO Pipe |
13 | Java NIO vs. IO |
Java NIO Pipe
A Java NIO Pipe is a one-way data connection between two threads. A Pipe
has a source channel and a sink channel. You write data to the sink channel. This data can then be read from the source channel.
Here is an illustration of the Pipe
principle:
Java NIO: Pipe Internals |
Creating a Pipe
You open a Pipe
by calling the Pipe.open()
method. Here is how that looks:
Pipe pipe = Pipe.open();
Writing to a Pipe
To write to a Pipe
you need to access the sink channel. Here is how that is done:
Pipe.SinkChannel sinkChannel = pipe.sink();
You write to a SinkChannel
by calling it‘s write()
method, like this:
String newData = http://www.mamicode.com/"New String to write to file..." + System.currentTimeMillis();>sinkChannel.write(buf); }
Reading from a Pipe
To read from a Pipe
you need to access the source channel. Here is how that is done:
Pipe.SourceChannel sourceChannel = pipe.source();
To read from the source channel you call its read()
method like this:
ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf);
The int
returned by the read()
method tells how many bytes were read into the buffer.
Java NIO Pipe