Java examples for File Path IO:File Channel
Test Pipe objects using a worker thread.
import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.Pipe; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.Random; public class Main { public static void main(String[] argv) throws Exception { WritableByteChannel out = Channels.newChannel(System.out); ReadableByteChannel workerChannel = startWorker(10); ByteBuffer buffer = ByteBuffer.allocate(100); while (workerChannel.read(buffer) >= 0) { buffer.flip();//from w ww. j av a 2 s . c om out.write(buffer); buffer.clear(); } } private static ReadableByteChannel startWorker(int reps) throws Exception { Pipe pipe = Pipe.open(); Worker worker = new Worker(pipe.sink(), reps); worker.start(); return (pipe.source()); } private static class Worker extends Thread { WritableByteChannel channel; private int reps; Worker(WritableByteChannel channel, int reps) { this.channel = channel; this.reps = reps; } public void run() { ByteBuffer buffer = ByteBuffer.allocate(100); try { for (int i = 0; i < this.reps; i++) { doSomeWork(buffer); while (channel.write(buffer) > 0) { } } this.channel.close(); } catch (Exception e) { e.printStackTrace(); } } private void doSomeWork(ByteBuffer buffer) { buffer.clear(); buffer.put("asdf".getBytes()); buffer.put("\r\n".getBytes()); buffer.flip(); } } }