NIO
BIO:阻塞IO
NIO:非阻塞IO
AIO;异步IO
Buffer缓冲区
Buffer和他的七个子类都是抽象类
Buffer的基本使用
因为Buffer和子类都是抽象类,所以子类有方法返回buffer对象
Buffer的核心方法
//创建字节缓冲区
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
//创建直接字节缓冲区
ByteBuffer byteBuffer1 = ByteBuffer.allocateDirect(1024);
//读入数据
byteBuffer.put("我爱Java".getBytes());
byteBuffer1.put("我爱Java".getBytes());
//转换状态
byteBuffer.flip();
byteBuffer1.flip();
//输出数据
System.out.println(new String(byteBuffer.array(), 0, byteBuffer.limit()));
//直接字节缓冲区不能使用这个方法
byte[] bytes =new byte[byteBuffer.limit()];
byteBuffer1.get(bytes);
System.out.println(new String(bytes,0,byteBuffer.limit()));
//清空
byteBuffer.clear();
byteBuffer1.clear();
直接字节缓冲区不能用对象.array()
position:位置
limit:限制
capacity:容量
position<=limit<=capacitSystem.out.println(“读取的位置”);
System.out.println(“position:”+buffer.position()+“limit:”+buffer.limit()+“capacity:”+buffer.capacity());y
在进行添加数据的操作时,limit和capacity指向最后的位置,而position指向开始的位置,当添加数据时,position+1,limit和capacity不变。
当进行读取数据的操作时,对象.flip();position指向0的位置,limit指向position的位置,capacity还是指向最后的位置,读一个数据,position+1,limit和capacity不变。
清空之后,对象.clear(),position指向0,limit和capacity指向最后,但是数据并没有清空,只是失效,下次添加的时候,直接覆盖。(变成了写状态)
调用压缩,对象.compact(),压缩到前面,position指向压缩的后一个位置,limit和capacity指向最后。(变成了写状态)
channel通道
创建FileChannel对象的四种方式。
//1文件字节流
FileOutputStream fileOutputStream= new FileOutputStream("d:\\hah.txt");
FileChannel channel=fileOutputStream.getChannel();
//2随机流
RandomAccessFile randomAccessFile = new RandomAccessFile("D:\\AAA.txt", "rw");
FileChannel channel=randomAccessFile.getChannel();
//3open()方法,参数Paths,mode
FileChannel channel=FileChannel.open(Paths.get("d:\\aaaa.txt"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
//4Channels工具类Channels.newChannel()返回的不是FileChannel类型,需要强转
FileChannel channel= (FileChannel)Channels.newChannel(new FileOutputStream("D:\\aa.txt"));
charset:编码器
如果读入到字节数组的末尾正好是中文的开头,下次就会出现乱码。所以需要编辑器操作。
//创建通道
FileChannel fileChannel = FileChannel.open(Paths.get("D:\\aaaa.txt"), StandardOpenOption.READ);
//编码器
CharsetDecoder charsetDecoder = Charset.forName("utf-8").newDecoder();
//创建CharBuffer缓冲区
CharBuffer charBuffer=CharBuffer.allocate(5);
//创建缓冲池
ByteBuffer byteBuffer = ByteBuffer.allocate(5);
while(fileChannel.read(byteBuffer)!=-1){
byteBuffer.flip();
//解码
charsetDecoder.decode(byteBuffer, charBuffer, false);
//由写转为读
charBuffer.flip();
System.out.println(charBuffer.toString());
//压缩
byteBuffer.compact();
charBuffer.clear();
}
fileChannel.close();
直接内存:allocateDirect(传输的数据越大,效率越高)
内存映射文件
分开映射
FileChannel readChannel=FileChannel.open(Paths.get("d:\\a12.jpg"), StandardOpenOption.READ);
FileChannel writeChannel=FileChannel.open(Paths.get("d:\\aa2.jpg"), StandardOpenOption.WRITE,StandardOpenOption.CREATE);
//直接映射
MappedByteBuffer map = readChannel.map(FileChannel.MapMode.READ_ONLY, 0, 4);
writeChannel.write(map);
MappedByteBuffer map1 = readChannel.map(FileChannel.MapMode.READ_ONLY,4,readChannel.size()-4);
writeChannel.write(map1);
readChannel.close();
writeChannel.close();
System.out.println("复制完毕");
NIO实现网络编程