Java NIO系列教程(二) Channel

    xiaoxiao2021-03-25  86

    本文转载至:http://ifeve.com/channels/

    Java NIO的通道类似流,但又有些不同:

    既可以从通道中读取数据,又可以写数据到通道。但流的读写通常是单向的。通道可以异步地读写。通道中的数据总是要先读到一个Buffer,或者总是要从一个Buffer中写入。

    正如上面所说,从通道读取数据到缓冲区,从缓冲区写入数据到通道。如下图所示:

    Channel的实现

    这些是Java NIO中最重要的通道的实现:

    FileChannelDatagramChannelSocketChannelServerSocketChannel

    FileChannel 从文件中读写数据。

    DatagramChannel 能通过UDP读写网络中的数据。

    SocketChannel 能通过TCP读写网络中的数据。

    ServerSocketChannel可以监听新进来的TCP连接,像Web服务器那样。对每一个新进来的连接都会创建一个SocketChannel。

    基本的 Channel 示例

    package com.zzg.channel; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class FileChannelUtil { public static void main(String[] args) { try{ File in = new File("D:\\in.txt"); File out = new File("D:\\out.txt"); if(in.createNewFile()){ //创建新文件 FileOutputStream is = new FileOutputStream(in); byte[] b = "湖南省益阳市南县*******".getBytes(); is.write(b, 0, b.length); } if(out.createNewFile()){ } FileInputStream is = new FileInputStream(in); FileOutputStream os = new FileOutputStream(out); FileChannel fis = is.getChannel(); FileChannel fos = os.getChannel(); ByteBuffer bytedata = ByteBuffer.allocate(100); while(fis.read(bytedata)!= -1){ // bytedata.flip(); //读取模式切换为写入模式 fos.write(bytedata); bytedata.clear();//清空缓存空间数据 } fis.close(); //关闭Filechannel 通道流 fos.close(); //关闭Filechannel 通道流 is.close(); //关闭FileInputStream 通道流 os.close(); //关闭FileOutputStream 通道流 }catch(Exception e ){ System.out.println("error message:"+e.getMessage()); } } } 注意 buf.flip() 的调用,首先读取数据到Buffer,然后反转Buffer,接着再从Buffer中读取数据。下一节会深入讲解Buffer的更多细节。
    转载请注明原文地址: https://ju.6miu.com/read-16667.html

    最新回复(0)