NIO学习之Channel

一、Channel基础

通道是一个对象,通过它可以读取和写入数据,Channel就是通向什么的道路,为数据的流向提供渠道;

在传统IO中,我们要读取一个文件中的内容使用Inputstream,该stream就是通道,不过在IO中这个通道是单向的,而NIO中Channel是双向的,既可用来进行读操作,又可用来进行写操作;无论读写都作用于Buffer。

1、将数据通过channdel输出到文件

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();
    }

2、通过channel将数据读入内存

 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();
    }

二、channel分类

FileChannel 从文件中读写数据。
DatagramChannel 能通过UDP读写网络中的数据。
SocketChannel 能通过TCP读写网络中的数据。
ServerSocketChannel可以监听新进来的TCP连接,像Web服务器那样。对每一个新进来的连接都会创建一个SocketChannel。

AsynchronousFileChannel:JDK1.7提供的异步操作文件类

猜你喜欢

转载自www.cnblogs.com/jalja/p/10855009.html