NIO之Channel

Channel 表示IO 源与目标打开的连接。Channel 类似于传统的“流”。只不过Channel 本身不能直接访问数据,Channel 只能与Buffer 进行交互。 

  通道的主要实现类
  java.nio.channels.Channel 接口:
  |--FileChannel
  |--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()
  
  通道之间的数据传输
  transferFrom()
  transferTo()
  
  分散(Scatter)与聚集(Gather)
  分散读取(Scattering Reads):将通道中的数据分散到多个缓冲区中
  聚集写入(Gathering Writes):将多个缓冲区中的数据聚集到通道中
  
  字符集:Charset
  编码:字符串 -> 字节数组
  解码:字节数组  -> 字符串

例子如下

package com.buerc.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.junit.Test;

public class TestChannel {
	//利用通道完成文件的复制(非直接缓冲区)
	@Test
	public void test1() throws IOException {
		Instant start=Instant.now();
		FileInputStream fis=new FileInputStream("G:\\虚拟机\\VMware-workstation_full_12.2.0.1269.exe");
		FileOutputStream fos=new FileOutputStream("G:\\虚拟机\\VMware.exe");
		
		FileChannel fc1=fis.getChannel();//为文件建立通道
		FileChannel fc2=fos.getChannel();//为文件建立通道
		
		ByteBuffer byteBuffer=ByteBuffer.allocate(1024);//非直接缓冲区
		while((fc1.read(byteBuffer))!=-1) {//从通道读取数据到缓冲区
			byteBuffer.flip();//切换为读模式
			fc2.write(byteBuffer);//将缓冲区数据写入通道
			byteBuffer.clear();
		}
		fc2.close();
		fc1.close();
		fos.close();
		fis.close();
		Instant end=Instant.now();
		System.out.println(Duration.between(start, end));//PT6.565S
	}
	
	//使用直接缓冲区完成文件的复制(内存映射文件)
	@Test
	public void test2() throws IOException  {
		Instant start=Instant.now();
		FileChannel fc1=FileChannel.open(Paths.get("G:\\虚拟机\\VMware-workstation_full_12.2.0.1269.exe"), StandardOpenOption.READ);//建立一个到文件的通道
		FileChannel fc2=FileChannel.open(Paths.get("G:\\虚拟机\\VMware.exe"), StandardOpenOption.WRITE,StandardOpenOption.READ);//建立一个到文件的通道
		
		//内存映射文件
		MappedByteBuffer mappedByteBuffer1=fc1.map(MapMode.READ_ONLY, 0, fc1.size());//将通道对应的文件直接映射到内存
		MappedByteBuffer mappedByteBuffer2=fc2.map(MapMode.READ_WRITE, 0, fc1.size());
		
		
		//直接对缓冲区中国的数据操作
		byte[] dst=new byte[mappedByteBuffer1.limit()];
		mappedByteBuffer1.get(dst);//从内存映射文件获取数据到指定字节数组
		mappedByteBuffer2.put(dst);//将字节数字内容写入内存映射文件所对应的通道的文件中去
		
		fc2.close();
		fc1.close();
		Instant end=Instant.now();
		System.out.println(Duration.between(start, end));//PT0.429S
	}
	
	//通道之间的数据传输(直接缓冲区)
	@Test
	public void test3() throws IOException {
		Instant start=Instant.now();
		FileChannel fc1=FileChannel.open(Paths.get("G:\\虚拟机\\VMware-workstation_full_12.2.0.1269.exe"), StandardOpenOption.READ);
		FileChannel fc2=FileChannel.open(Paths.get("G:\\虚拟机\\VMware.exe"), StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE);
		
//		fc1.transferTo(0, fc1.size(), fc2);//直接将通道1中的数据传输到通道2中对应的文件
		fc2.transferFrom(fc1, 0, fc1.size());
		Instant end=Instant.now();
		System.out.println(Duration.between(start, end));//PT0.429S
	}
	
	//分散和聚集
	@Test
	public void test4() throws IOException {
		RandomAccessFile ras=new RandomAccessFile("1.txt", "rw");
		
		//获取通道
		FileChannel fc1=ras.getChannel();
		
		ByteBuffer byteBuffer1=ByteBuffer.allocate(1024);
		ByteBuffer byteBuffer2=ByteBuffer.allocate(1024);
		ByteBuffer[] byteBuffers= {byteBuffer1,byteBuffer2};
		
		//分散读取
		fc1.read(byteBuffers);
		for (ByteBuffer byteBuffer : byteBuffers) {
			byteBuffer.flip();
		}
		System.out.println(new String(byteBuffers[0].array()));
		System.out.println("----------------------");
		System.out.println(new String(byteBuffers[1].array()));
		RandomAccessFile ras2=new RandomAccessFile("2.txt", "rw");
		FileChannel fc2=ras2.getChannel();
		
		//聚集写入
		fc2.write(byteBuffers);
		fc2.close();
		ras2.close();
		fc1.close();
		ras.close();
	}
	
	@Test
	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()+"\t"+entry.getValue());
		}
	}
	
	@Test//字符集
	public void test6() throws IOException {
		Charset charset=Charset.forName("UTF-8");//指定字符编码集
		CharsetEncoder charsetEncoder=charset.newEncoder();//获取编码器
		CharsetDecoder charsetDecoder=charset.newDecoder();//获取解码器
		
		CharBuffer in=CharBuffer.allocate(1024);
		in.put("helloworld");
		in.flip();
		ByteBuffer byteBuffer=charsetEncoder.encode(in);
		for (int i = 0; i < in.limit(); i++) {
			System.out.println(byteBuffer.get(i));
		}
		
		CharBuffer out=charsetDecoder.decode(byteBuffer);
		
		for (int i = 0; i <out.limit(); i++) {
			System.out.print(out.get());
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值