1、Channel基础服务器
通道是一个对象,经过它能够读取和写入数据,Channel就是通向什么的道路,为数据的流向提供渠道;网络
在传统IO中,咱们要读取一个文件中的内容使用Inputstream,该stream就是通道,不过在IO中这个通道是单向的,而NIO中Channel是双向的,既可用来进行读操做,又可用来进行写操做;不管读写都做用于Buffer。异步
一、将数据经过channdel输出到文件spa
private static void writer( )throws IOException{ String str="I Love China"; byte [] message=str.getBytes("UTF-8"); FileOutputStream fout = new FileOutputStream( filePath ); FileChannel fc = fout.getChannel(); ByteBuffer buffer = ByteBuffer.allocate( 1024 ); for (int i=0; i<message.length; ++i) { buffer.put( message[i] ); } buffer.flip(); fc.write( buffer ); fout.close(); }
二、经过channel将数据读入内存code
private static void read( )throws IOException{ FileInputStream inputStream=new FileInputStream(filePath); FileChannel channel=inputStream.getChannel(); ByteBuffer buffer = ByteBuffer.allocate( 1024 ); channel.read(buffer); String msg=new String(buffer.array(),"UTF-8"); System.out.println(msg); inputStream.close(); }
2、channel分类对象
FileChannel 从文件中读写数据。
DatagramChannel 能经过UDP读写网络中的数据。
SocketChannel 能经过TCP读写网络中的数据。
ServerSocketChannel能够监听新进来的TCP链接,像Web服务器那样。对每个新进来的链接都会建立一个SocketChannel。blog
AsynchronousFileChannel:JDK1.7提供的异步操做文件类ip