See More

-------------------------------- Pipe | -------------------------------- # jdk4ÒÔǰ¹ÜµÀÁ÷ÐèҪͨ¹ý PipedInputStream, PipedOutputStream ²Ù×÷Á÷À´Íê³ÉͨÐÅ # jdk4ÒÔºó, ÌṩÁË Pipe, ͨ¹ý²Ù×÷»º³åÇøÀ´Í¨ÐÅ * Pipe¾ß±¸Ò»¸ösourcechannelºÍÒ»¸ösinkchannel * sinkchannel¸ºÔðÍù¹ÜµÀдÈëÊý¾Ý,sourcechannel¸ºÔð´Ó¹ÜµÀ¶ÁÈ¡Êý¾Ý * ǧÍò²»ÄÜͬһ¸öÏ̼߳ȶÁÓÖд£¬ÒòΪ¶ÁÈ¡²Ù×÷»á×èÈûÏ̡߳£Í¬Ò»¸öÏ̲߳Ù×÷¹ÜµÀÁ÷»áÔì³ÉÏß³ÌËÀËø # ¹¹½¨ //´ò¿ªÒ»¸ö¹ÜµÀ Pipe pipe = Pipe.open(); //´Ó¹ÜµÀ»ñȡдÈëÊý¾ÝµÄchannel SinkChannel sinkChannel = pipe.sink(); //´Ó¹ÜµÀ»ñÈ¡¶ÁÈ¡Êý¾ÝµÄchannel SourceChannel sourceChannel = pipe.source(); # ÑÝʾdemo import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.Pipe; import java.nio.channels.Pipe.SinkChannel; import java.nio.channels.Pipe.SourceChannel; import java.nio.charset.StandardCharsets; import java.util.Scanner; public class Main { public static void main(String[] args) throws Exception { //´ò¿ªÒ»¸ö¹ÜµÀ Pipe pipe = Pipe.open(); //´Ó¹ÜµÀ»ñȡдÈëÊý¾ÝµÄchannel SinkChannel sinkChannel = pipe.sink(); //´Ó¹ÜµÀ»ñÈ¡¶ÁÈ¡Êý¾ÝµÄchannel SourceChannel sourceChannel = pipe.source(); //ÐÂÆô¶¯Ïß³ÌÄ£Äâ¶Á new Thread(() -> { try { ByteBuffer byteBuffer = ByteBuffer.allocate(1024); while(true) { //·µ»Øint£¬±íʾ¶ÁÈ¡µ½Á˶àÉÙ×Ö½ÚµÄÊý¾Ý£¬Èç¹û¹ÜµÀûÓÐÊý¾Ý£¬¸Ã·½·¨»á×èÈû sourceChannel.read(byteBuffer); //¶ÁÈ¡Íê±Ïºó¸´Î»£¬ÓÉд¸ÄΪ¶Á byteBuffer.flip(); byte bytes[] = new byte[byteBuffer.remaining()]; byteBuffer.get(bytes); System.out.println(Thread.currentThread().getName() + "-ÊÕµ½ÏûÏ¢:" + new String(bytes,StandardCharsets.UTF_8)); //Çå¿Õ»º³åÇø£¬ÓÉд¸ÄΪ¶Á byteBuffer.clear(); } } catch (IOException e) { e.printStackTrace(); } }) .start(); //µ±Ç°Ïß³ÌÄ£Äâд try(Scanner scanner = new Scanner(System.in)){ ByteBuffer byteBuffer = ByteBuffer.allocate(1024); while(true) { String line = scanner.nextLine(); System.out.println(Thread.currentThread().getName() + "-·¢ËÍÏûÏ¢:" + line); byteBuffer.put(line.getBytes(StandardCharsets.UTF_8)); byteBuffer.flip(); sinkChannel.write(byteBuffer); byteBuffer.clear(); } } } }