Java NIO 之 通道(Channel)

通道(Channel)

通道(Channel):由 java.nio.channels 包定义的。Channel 表示 IO 源与目标打开的连接。Channel 类似于传统的“流”。只不过 Channel本身不能直接访问数据,Channel 只能与Buffer 进行交互。

(1)早期操作系统磁盘IO

 (2)使用DMA(直接存储器存储)

问题:对于非常大型的IO应用程序,对进行大量的读写请求,会建立大量的DMA总线,造成总线冲突。

(3)通道(完全独立的处理器,专门用于IO操作)

通道Channel 本身不存储数据,因此需要配合缓冲区进行传输。

通道的主要实现类

java.nio.channels.Channel 接口:
        |--FileChannel(本地IO,其他都是网络IO)
        |--SocketChannel 
        |--ServerSocketChannel
        |--DatagramChannel

获取通道的三种方式

  • 1. Java 针对支持通道的类提供了 getChannel() 方法;

           本地 IO:
               FileInputStream/FileOutputStream
               RandomAccessFile

          网络IO
               Socket
               ServerSocket
               DatagramSocket

  • 2. 在 JDK 1.7 中的 NIO.2 针对各个通道提供了静态方法 open();
  • 3. 在 JDK 1.7 中的 NIO.2 的 Files 工具类的 newByteChannel()。

例子1:利用通道完成文件的复制(非直接缓冲区)

public void copyFileByChannel() throws IOException {
    FileInputStream inputStream = new FileInputStream("demo/text.txt");
    FileOutputStream outputStream = new FileOutputStream("demo/textout.txt");

    //1. 获取通道
    FileChannel inputStreamChannel = inputStream.getChannel();
    FileChannel outputStreamChannel = outputStream.getChannel();

    //2. 分配指定大小的缓冲区
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    //3. 将通道中的数据存入缓冲区中
    while (inputStreamChannel.read(buffer) != -1){
        buffer.flip(); //切换读取数据的模式
        outputStreamChannel.write(buffer);
        buffer.clear();

    }
    inputStreamChannel.close();
    outputStreamChannel.close();
    inputStream.close();
    outputStream.close();
}

例子2:使用直接缓冲区完成文件的复制(内存映射文件)

public void test2() throws IOException{//2127-1902-1777
	long start = System.currentTimeMillis();
	
	FileChannel inChannel = FileChannel.open(Paths.get("d:/1.mkv"), StandardOpenOption.READ);
	FileChannel outChannel = FileChannel.open(Paths.get("d:/2.mkv"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE);
	
	//内存映射文件
	MappedByteBuffer inMappedBuf = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
	MappedByteBuffer outMappedBuf = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size());
	
	//直接对缓冲区进行数据的读写操作
	byte[] dst = new byte[inMappedBuf.limit()];
	inMappedBuf.get(dst);
	outMappedBuf.put(dst);
	
	inChannel.close();
	outChannel.close();
	
	long end = System.currentTimeMillis();
	System.out.println("耗费时间为:" + (end - start));
}

 通道之间的数据传输

例子:通道之间的数据传输(直接缓冲区)

//通道之间的数据传输(直接缓冲区)
public void test3() throws IOException{
	FileChannel inChannel = FileChannel.open(Paths.get("d:/1.mkv"), StandardOpenOption.READ);
	FileChannel outChannel = FileChannel.open(Paths.get("d:/2.mkv"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE);
	
//		inChannel.transferTo(0, inChannel.size(), outChannel);
	outChannel.transferFrom(inChannel, 0, inChannel.size());
	
	inChannel.close();
	outChannel.close();
}

分散(Scatter)与聚集(Gather)

分散读取(Scattering Reads):将通道中的数据分散到多个缓冲区中;

注意:按照缓冲区的顺序,从 Channel 中读取的数据依次将 Buffer 填满。 

聚集写入(Gathering Writes):将多个缓冲区中的数据聚集到通道中。

注意:按照缓冲区的顺序,写入 position 和 limit 之间的数据到 Channel 。 

例子:分散和聚集 

public void test4() throws IOException{
    RandomAccessFile raf1 = new RandomAccessFile("demo/text.txt", "rw");

    //1. 获取通道
    FileChannel channel1 = raf1.getChannel();

    //2. 分配指定大小的缓冲区
    ByteBuffer buf1 = ByteBuffer.allocate(100);
    ByteBuffer buf2 = ByteBuffer.allocate(1024);

    //3. 分散读取
    ByteBuffer[] bufs = {buf1, buf2};
    channel1.read(bufs);

    for (ByteBuffer byteBuffer : bufs) {
        byteBuffer.flip();
    }

    System.out.println(new String(bufs[0].array(), 0, bufs[0].limit()));
    System.out.println("-----------------");
    System.out.println(new String(bufs[1].array(), 0, bufs[1].limit()));

    //4. 聚集写入
    RandomAccessFile raf2 = new RandomAccessFile("demo/text2.txt", "rw");
    FileChannel channel2 = raf2.getChannel();

    channel2.write(bufs);
}

字符集:Charset

编码:字符串 -> 字节数组;

解码:字节数组  -> 字符串

例子1:获取系统支持的所有编码格式

public void test5(){
	Map<String, Charset> map = Charset.availableCharsets();
	
	Set<Entry<String, Charset>> set = map.entrySet();
	
	for (Entry<String, Charset> entry : set) {
		System.out.println(entry.getKey() + "=" + entry.getValue());
	}
}

例子2:获取系统支持的所有编码格式

public void test6() throws IOException{
    Charset cs1 = Charset.forName("GBK");

    //获取编码器
    CharsetEncoder ce = cs1.newEncoder();

    //获取解码器
    CharsetDecoder cd = cs1.newDecoder();

    CharBuffer cBuf = CharBuffer.allocate(1024);
    cBuf.put("你好啊!");
    // flip()函数的作用是将写模式转变为读模式,
    // 即将写模式下的Buffer中内容的最后位置变为读模式下的limit位置,作为读越界位置,
    // 同时将当前读位置置为0,表示转换后重头开始读,同时再消除写模式下的mark标记
    cBuf.flip();

    //编码
    ByteBuffer bBuf = ce.encode(cBuf);

    for (int i = 0; i < 6; i++) {
        System.out.println(bBuf.get());
    }

    //解码
    bBuf.flip();
    CharBuffer cBuf2 = cd.decode(bBuf);
    System.out.println(cBuf2.toString());
    System.out.println("------------------------------------------------------");

    Charset cs2 = Charset.forName("GBK");
    bBuf.flip();
    CharBuffer cBuf3 = cs2.decode(bBuf);
    System.out.println(cBuf3.toString());
}

输出结果:

-60
-29
-70
-61
-80
-95
你好啊
------------------------------------------------------
你好啊

猜你喜欢

转载自blog.csdn.net/kaizuidebanli/article/details/84306341