目录
java nio(非阻塞io):nio与原来的io有同样的作用和目的,但是使用的方式完全不同。nio支持面向缓冲区的、基于通道的io操作。nio将以更加高效的方式进行文件的读写操作。
io | nio |
---|---|
面向流 | 面向缓冲区 |
单向传输 | 双向传输 |
阻塞io | 非阻塞io |
无 | 选择器selectors |
概括:channel负责传输,buffer负责存储
在java nio中负责数据的存取,缓冲区就是个数组。用于存储不同类型的数据。
根据类型的不同(boolean除外),提供了相应类型的缓冲区:bytebuffer、charbuffer、shortbuffer、intbuffer、longbuffer、floatbuffer、doublebuffer
allocate(int capacity)
//创建一个大小为1024的byte类型的缓冲区 bytebuffer bytebuffer= bytebuffer.allocate(1024);
put存数据到缓冲区,get从缓冲区取数据,必须通过flip从读模式转换成写模式,才可以get
bytebuffer.put("abcde".getbytes()); bytebuffer.flip();//转换成写模式 byte[] dst = new byte[5]; bytebuffer.get(dst); system.out.println(new string(dst,0,5));
<1>获取 buffer 中的数据
get() :读取单个字节
get(byte[] dst):批量读取多个字节到 dst 中
get(int index):读取指定索引位置的字节(不会移动 position)
<2>放入数据到 buffer 中
put(byte b):将给定单个字节写入缓冲区的当前位置
put(byte[] src):将 src 中的字节写入缓冲区的当前位置
put(int index, byte b):将指定字节写入缓冲区的索引位置(不会移动 position)
capacity:容量,表示缓冲区中最大存储数据的容量。一旦申明不能改变。
limit:界限,表示缓冲区中可以操作数据的大小。(limit后面的数据不能读写)
position:位置,表示缓冲区中正在操作数据的位置。
mark:标记,表示记录当前position的位置。可以通过rest()恢复到mark的位置
0=<mark<=position <= limit <= capacity
bytebuffer bytebuffer = bytebuffer.allocate(1024); system.out.println("--------------初始创建缓冲区allocate()----------------"); system.out.println(bytebuffer.position());//输出0 system.out.println(bytebuffer.limit());//输出1024 system.out.println(bytebuffer.capacity());//输出1024 system.out.println("--------------写模式put()----------------"); bytebuffer.put("abcde".getbytes()); system.out.println(bytebuffer.position());//输出5 system.out.println(bytebuffer.limit());//输出1024 system.out.println(bytebuffer.capacity());//输出1024 system.out.println("--------------切换到读模式flip()----------------"); bytebuffer.flip();//将缓冲区的.limit设置为position,并将positions设为 0 system.out.println(bytebuffer.position());//输出0 system.out.println(bytebuffer.limit());//输出5 system.out.println(bytebuffer.capacity());//输出1024 system.out.println("--------------开始读数据get()----------------"); byte[] dst = new byte[5]; bytebuffer.get(dst); system.out.println(new string(dst,0,5)); system.out.println(bytebuffer.position());//输出5 system.out.println(bytebuffer.limit());//输出5 system.out.println(bytebuffer.capacity());//输出1024 system.out.println("--------------重新读数据rewind()----------------"); bytebuffer.rewind();//将position设为 0 system.out.println(bytebuffer.position());//输出0 system.out.println(bytebuffer.limit());//输出5 system.out.println(bytebuffer.capacity());//输出1024 system.out.println("-------------清空缓冲区数据clear()----------------"); bytebuffer.clear();//清空缓冲区,但是缓冲区的数据依然存在,只是位置、界限变成最初状态,这个方法主要用来重新写数据到缓存 system.out.println(bytebuffer.position());//输出0 system.out.println(bytebuffer.limit());//输出1024 system.out.println(bytebuffer.capacity());//输出1024 byte[] dst1 = new byte[2]; bytebuffer.get(dst1); system.out.println(new string(dst1));//输出ab system.out.println("--------------标记位置mark(),恢复到标记的位置reset()----------------"); bytebuffer.mark(); //对缓冲区设置标记 bytebuffer.get(dst1); system.out.println(new string(dst1));//输出cd bytebuffer.reset();//将 position 回复到以前设置的 mark 所在的位置 bytebuffer.get(dst1); system.out.println(new string(dst1));//又输出cd
hasremaining:是否还有数据可以读,返回true或false,代表limit-position是否大于0
remaining:还可以读多少个数据,代表limit-position的值
if(bytebuffer.hasremaining()){ system.out.println(bytebuffer.remaining() ); }
<1>非直接缓冲区:通过allocate()方法分配非直接缓冲区,这个缓存是建立在jvm的内容中的。
我们可以从图看到非直接缓冲区的缺点:中间有个copy过程,所以效率较低。
<2>直接缓冲区:通过allocatedirect()方法分配直接缓冲区,将缓冲区建立在物理内存中,可以提高效率。
我们可以从图看到多开辟了个物理内存,这导致分配和销毁数据耗费的资源很大,并且把数据写给映射文件以后,数据就不归我们管了,数据什么时候从映射文件存到磁盘完全由操作系统决定。应用程序和映射文件之间的连接断开是由垃圾回收机制释放的,可能导致应用程序要很久才断开连接。
使用场景:数据需要长时间在内存中进行操作,或者大数据
直接字节缓冲区可以通过调用此类的allocatedirect()工厂方法来创建。
bytebuffer bytebuffer = bytebuffer.allocatedirect(1024); boolean isdirect = bytebuffer.isdirect();//isdirect=true;
还可以通过filechannel的map方法将文件区域直接映射到内存中来创建,该方法返回mappedbytebuffer。(具体例子看4大节的例子2)
字符集charset的编码(字符串转换成字节数组)和解码(字节数据转换成字符串)
例子: 把字符串缓冲区编码转换成字节缓冲区,再解码转换成字符串缓冲区
@test public void niotest5() { //获取编码的字符类型 charset gbkcharset = charset.forname("gbk"); //生成字符串缓冲区 charbuffer charbuf1= charbuffer.allocate(1024); charbuf1.put("牛逼!!"); charbuf1.flip(); //把charbuf编码成bytebuf,生成中间的字节缓冲区 bytebuffer bytebuf = gbkcharset.encode(charbuf1); //获取解码的字符类型 charset utf8charset = charset.forname("gbk");//如果换成utf-8等其他类型就会乱码 //把bytebuf解码成charbuf,把中间的字节缓冲区转换成字符串缓冲区 charbuffer charbuf2 = utf8charset.decode(bytebuf); system.out.println(charbuf2.tostring()); }
通道:用于源节点与目标节点的连接,在java nio中负责缓冲区中数据的传输。
channel是完全独立的处理器,附属于cpu,专门用于io操作。有效提高cpu利用率。
注意:channel只能与buffer交互。
bytebuffer buf=...; //缓冲区写到channel outchannel.write(buf); //channel写到buf inchannel.read(buf)
java.nio.channels.channel接口主要实现类:
<1>下面几个类可以通过getchannel()获得channel
本地io:
- fileinputstream/fileoutputstream
- randomaccessfile
网络io:
- socket
- serversocket
- datagramsocket
<2>通道的静态方法open()
<3>file工具类的newbytechannel()
这里的文件流指的是fileinputstream/fileoutputstream。
通过文件流的getchannel()获得filechannel,两个filechannel之间进行传输数据,缓冲区为非直接缓冲区
eg1:复制1.jpg,生成2.jpg
@test public void niotest1() { try(fileinputstream fis = new fileinputstream("1.jpg");//放在项目根目录下 fileoutputstream fos = new fileoutputstream("2.jpg");//最后要生成的文件名 //1、通过文件流获取通道 filechannel inchannel =fis.getchannel(); filechannel outchannel =fos.getchannel();){ //2、通过bytebuffer.allocate分配指定大小的非直接缓冲区 bytebuffer buf =bytebuffer.allocate(1024); //3、将in通道中的数据存入缓存 while(inchannel.read(buf)!=-1){ buf.flip();//把缓冲区切换成读模式 //4、将缓冲区的数据写入out通道 outchannel.write(buf); buf.clear();//清空緩存 } } catch (ioexception e) { e.printstacktrace(); } }
通过filechannel.open()获得filechannel,两个filechannel之间进行传输数据,缓冲区为直接缓冲区
eg2:复制1.jpg,生成2.jpg
@test public void niotest2() { //1、通过filechannel.open获取通道 try(filechannel inchannel=filechannel.open(paths.get("1.jpg"), standardopenoption.read); filechannel outchannel = filechannel.open(paths.get("2.jpg"),standardopenoption.read,standardopenoption.write,standardopenoption.create)){ //2、通过filechannel的map方法获取直接缓冲区,即内存映射文件 mappedbytebuffer inmappedbuf = inchannel.map(mapmode.read_only, 0, inchannel.size()); mappedbytebuffer outmappedbuf = outchannel.map(mapmode.read_write, 0, inchannel.size()); //3、直接对缓冲区进行操作,无需通过channel byte[] dst= new byte[inmappedbuf.limit()];// inchannel.size()和inmappedbuf.limit()一样的 inmappedbuf.get(dst); outmappedbuf.put(dst); } catch (ioexception e) { e.printstacktrace(); } }
注意:非直接缓冲区方式,有时候垃圾回收机制不能及时运行的话,导致资源一直连接着,没有断开。但是确实直接缓冲区比非直接缓冲区效率高很多。
eg2可以简化一下缓冲区操作步骤,直接利用通道之间的数据传输方法---transferfrom()、transferto()
eg3:复制1.jpg,生成2.jpg
@test public void niotest3() { //1、通过filechannel.open获取通道 try(filechannel inchannel=filechannel.open(paths.get("1.jpg"), standardopenoption.read); filechannel outchannel = filechannel.open(paths.get("2.jpg"),standardopenoption.read,standardopenoption.write,standardopenoption.create)){ //inchannel.transferto(0,inchannel.size(),outchannel);//transferto底层和上面例子2差不多 outchannel.transferfrom(inchannel,0,inchannel.size());//和transferto一样,只是方向反一下而已 } catch (ioexception e) { e.printstacktrace(); } }
分散(scatter):将通道中的数据分散读取到多个缓冲区中
聚集(gather)将多个缓冲区的数据聚集到通道中
eg4:把1.txt通过channel读取到多个缓冲区中,然后把多个缓冲区的数据通过channel读到2.txt
@test public void niotest4() throws ioexception { //一、将通道中的数据分散读取到多个缓冲区中 randomaccessfile inraf = new randomaccessfile("1.txt", "rw");//1.txt为要读取的文件 //1、通过randomaccessfile获取通道 filechannel inchannel = inraf.getchannel(); //2、分配多个直接缓冲区,放到数组中 bytebuffer[] bufs = {bytebuffer.allocate(102), bytebuffer.allocate(1024)}; //3、将通道中的数据分散读取到多个缓冲区中 inchannel.read(bufs); //验证一下bufs的数据 arrays.stream(bufs).foreach(buf -> buf.flip());//先把每个缓冲区转换成读模式 arrays.stream(bufs).foreach(buf -> system.out.println(new string(buf.array()) + "\n----------------"));//可以看到,把1.txt的内容打印出来了 //关闭流 inraf.close(); inchannel.close(); //二、将多个缓冲区的数据聚集到通道中 randomaccessfile outraf = new randomaccessfile("2.txt", "rw");//2.txt为要写入的文件,会自动创建 //1、通过randomaccessfile获取通道 filechannel outchannel = outraf.getchannel(); outchannel.write(bufs); //关闭流 outraf.close(); outchannel.close(); }
传统的 io 流都是阻塞式的。也就是说,当一个线程调用 read() 或 write()
时,该线程被阻塞,直到有一些数据被读取或写入,该线程在此阻塞期间不
能执行其他任务。
使用nio完成阻塞网络通信的两个核心: 1、通道channel:负责连接 java.nio.channels.channel接口 | -- selectablechannel类 | -- socketchannel类 | -- serersocketchannel类 | -- datagramchannel类 | -- pipe.sinkchannel类 | -- pipe.sourcechannel类 2、缓冲区buffer:负责数据的存取
eg: 客户端发送一个图片给服务端,服务端保存到本地,并返回应答。这里还没有用到selector(先运行服务端,再运行客户端)
@test public void client() throws ioexception { //1、获取网络传输客户端通道,默认都是阻塞通讯 socketchannel socketchannel = socketchannel.open(new inetsocketaddress("127.0.0.1", 9898)); //2、分配指定大小的缓冲区 bytebuffer buf = bytebuffer.allocate(1024); //3、读取本地文件到缓冲区 filechannel inchannel = filechannel.open(paths.get("1.jpg"), standardopenoption.read); while (inchannel.read(buf) != -1) { buf.flip(); //4、将缓冲区的数据写入socketchannel socketchannel.write(buf); buf.clear(); } //5、告诉服务端我已经发完了,如果不写这个,服务端就一直监听客户端数据,导致阻塞 socketchannel.shutdownoutput(); //6、接收反馈 int len=0; while((len=socketchannel.read(buf))!=-1){ buf.flip(); system.out.println(new string(buf.array(),0,len)); buf.clear(); } //5、关闭 socketchannel.close(); inchannel.close(); } @test public void server() throws ioexception { //1、获取网络传输服务端通道,并绑定本地连接的端口 serversocketchannel serversocketchannel = serversocketchannel.open(); serversocketchannel.bind(new inetsocketaddress(9898)); //2、获取客户端连接的通道(阻塞监听) socketchannel clientsocketchannel = serversocketchannel.accept(); //3、获取写数据到本地的文件通道 filechannel filechannel = filechannel.open(paths.get("2.jpg"),standardopenoption.write,standardopenoption.create); //4、分配制定大小的非直接缓冲区 bytebuffer buf = bytebuffer.allocate(1024); //5、接收客户端的数据到缓冲区 while(clientsocketchannel.read(buf)!=-1){ buf.flip(); //把缓冲区的数据保存到本地 filechannel.write(buf); buf.clear(); } //6、反馈给客户端 buf.put("服务端接收数据成功".getbytes()); buf.flip(); clientsocketchannel.write(buf); //关闭 serversocketchannel.close(); clientsocketchannel.close(); filechannel.close(); }
nio 可以让服务器端使用一个或有限几个线程来同时处理连接到服务器端的所有客户端。当线程从某通道进行读写数据时,若没有数据可用时,该线程可以进行其他任务。
使用nio完成非阻塞网络通信的三个核心: 1、通道channel:负责连接 java.nio.channels.channel接口 | -- selectablechannel | -- socketchannel | -- serersocketchannel | -- datagramchannel | -- pipe.sinkchannel | -- pipe.sourcechannel 2、缓冲区buffer:负责数据的存取 3、选择器selector:是selectablechannel的多路复用器,用于监控selectalechannel的io状况。selector 可使一个单独的线程管理多个 channel。selector 是非阻塞 io 的核心。
selector selector= selector.open();//创建选择器 selectablechannel.register(selector selector,int ops);//selectablechannel注册到选择器
ops:就是选择器监听这个channel的事件类型,如果这个channel准备好了,就放行,否则不管
selectionkey.op_write:等待写数据的通道可以说是“ 写就绪 ”
方 法 | 描 述 |
---|---|
set |
所有的 selectionkey 集合。代表注册在该selector上的channel |
selectedkeys() | 被选择的 selectionkey 集合。返回此selector的已选择键集 |
int select() | 监控所有注册的channel,当它们中间有需要处理的 io 操作时,该方法返回,并将对应得的 selectionkey 加入被选择的 |
selectionkey | 集合中,该方法返回这些 channel 的数量。 |
int select(long timeout) | 可以设置超时时长的 select() 操作 |
int selectnow() | 执行一个立即返回的 select() 操作,该方法不会阻塞线程 |
selector wakeup() | 使一个还未返回的 select() 方法立即返回 |
void close() | 关闭该选择器 |
方 法 | 描 述 |
---|---|
int interestops() | 获取感兴趣事件集合 |
int readyops() | 获取通道已经准备就绪的操作的集合 |
selectablechannel channel() | 获取注册通道 |
selector selector() | 返回选择器 |
boolean isreadable() | 检测 channal 中读事件是否就绪 |
boolean iswritable() | 检测 channal 中写事件是否就绪 |
boolean isconnectable() | 检测 channel 中连接是否就绪 |
boolean isacceptable() | 检测 channel 中接收是否就绪 |
eg: 服务端一直监听客户端,可以同时多个客户端发送数据给服务端(先启动服务端,再启动客户端)
@test public void client() throws ioexception { //1、获取网络传输客户端通道、并切换为非阻塞模式 socketchannel socketchannel = socketchannel.open(new inetsocketaddress("127.0.0.1", 9898)); socketchannel.configureblocking(false); //2、分配指定大小的缓冲区,并写入数据 bytebuffer buf = bytebuffer.allocate(1024); buf.put("客服端的数据".getbytes()); //4、将缓冲区的数据写入socketchannel buf.flip(); socketchannel.write(buf); //5、关闭 socketchannel.close(); } @test public void server() throws ioexception { //1、获取网络传输服务端通道,并设置为非阻塞模式,并绑定本地连接的端口, serversocketchannel serversocketchannel = serversocketchannel.open(); serversocketchannel.configureblocking(false); serversocketchannel.bind(new inetsocketaddress(9898)); //2、获取选择器,并把服务端通道绑定到选择器 selector selector= selector.open(); serversocketchannel.register(selector, selectionkey.op_accept);//指定服务端监听接收事件(此时还没有客服连接进来,所以是未就绪) //3、selector.select()已经就绪的channel, while(selector.select()>0){ system.out.println("有就绪好的channel了,我进来了"); //4、获取当前选择器中所有已经注册的“选择键”,也就是已经就绪的监听事件,步骤2已经注册了serversocketchannel iterator<selectionkey> skiterator = selector.selectedkeys().iterator(); while (skiterator.hasnext()){ //5、获取准备就绪的事件 selectionkey sk = skiterator.next(); //6、判断具体是什么事件准备就绪 if(sk.isacceptable()){ //7、如果是接收就绪,获取客户端连接,并切换为非阻塞模式 socketchannel clientsocketchannel = serversocketchannel.accept(); clientsocketchannel.configureblocking(false); //8、将该通道注册到选择器上 clientsocketchannel.register(selector,selectionkey.op_read); }else if(sk.isreadable()){ //9、获取当前选择器上“读就绪”状态的通道 socketchannel clientsocketchannel = (socketchannel) sk.channel(); //10、读取数据 bytebuffer buf = bytebuffer.allocate(1024); int len=0; while((len=clientsocketchannel.read(buf))!=-1){ buf.flip(); system.out.println(new string(buf.array(),0,len)); buf.clear(); } //关闭 clientsocketchannel.close(); } //注意,要删除此次的选择键,不然步骤4又循环到这个选择键 selector.selectedkeys().remove(sk); } } }
java nio中的datagramchannel是一个能收发udp包的通道。
eg: 服务端一直监听客户端,可以同时多个客户端发送数据给服务端(先启动服务端,再启动客户端)
@test public void client() throws ioexception { //1、获取网络传输客户端通道、并切换为非阻塞模式 datagramchannel clientdatagramchannel = datagramchannel.open(); clientdatagramchannel.configureblocking(false); //2、分配指定大小的缓冲区,并写入数据 bytebuffer buf = bytebuffer.allocate(1024); buf.put("客服端的数据".getbytes()); //4、将缓冲区的数据写入socketchannel buf.flip(); clientdatagramchannel.send(buf,new inetsocketaddress("127.0.0.1",9898)); //5、关闭 clientdatagramchannel.close(); } @test public void server() throws ioexception { //1、获取网络传输服务端通道,并设置为非阻塞模式,并绑定本地连接的端口, datagramchannel serverdatagramchannel = datagramchannel.open(); serverdatagramchannel.configureblocking(false); serverdatagramchannel.bind(new inetsocketaddress(9898)); //2、获取选择器,并把服务端通道绑定到选择器 selector selector= selector.open(); serverdatagramchannel.register(selector, selectionkey.op_read);//指定服务端监听读事件(此时还没有客服连接进来,所以是未就绪) //3、selector.select()已经就绪的channel, while(selector.select()>0){ system.out.println("有就绪好的channel了,我进来了"); //4、获取当前选择器中所有已经注册的“选择键”,也就是已经就绪的监听事件,步骤2已经注册了serversocketchannel iterator<selectionkey> skiterator = selector.selectedkeys().iterator(); while (skiterator.hasnext()){ //5、获取准备就绪的事件 selectionkey sk = skiterator.next(); //6、判断具体是什么事件准备就绪 if(sk.isreadable()){ //7、读取数据到缓冲区 bytebuffer buf = bytebuffer.allocate(1024); serverdatagramchannel.receive(buf); buf.flip(); system.out.println(new string(buf.array(),0,buf.limit())); } //注意,要删除此次的选择键,不然步骤4又循环到这个选择键 selector.selectedkeys().remove(sk); } } }
java nio 管道是2个线程之间的单向数据连接。
pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。
eg: 写数据到sinkechannel,从sourcechannel拿数据
@test public void pipetest() throws ioexception { //0、获取管道 pipe pipe = pipe.open(); //1、获取sink channel ,用来写数据 pipe.sinkchannel sinkchannel = pipe.sink(); //2、创建缓冲区,并写数据,用来把数据存到channel bytebuffer writebuf = bytebuffer.allocate(1024); writebuf.put("我写数据进管道".getbytes()); //3、把缓冲区的数据写到channel writebuf.flip(); sinkchannel.write(writebuf); /**==================假装下面是另一个线程=========================**/ //1、获取source channel,用来读数据 pipe.sourcechannel sourcechannel = pipe.source(); //2、创建缓冲区,用来把channel的数据写到缓冲区 bytebuffer readbuf = bytebuffer.allocate(1024); //3、把channel的数据写到buf sourcechannel.read(readbuf); //4、输出buf的数据 readbuf.flip(); system.out.println(new string(readbuf.array(),0,readbuf.limit())); //关闭 sinkchannel.close(); sourcechannel.close(); }
如对本文有疑问, 点击进行留言回复!!
解决idea中出现“illegal character U+200B” 问题
荐 为什么加了@Transactional注解,事务没有回滚?
Attribute ‘sklearn.linear_model._logistic.LogisticRegression.multi_class‘ must be explicitly set to
Java/Python实现 LeetCode剑指Offer 14-I.剪绳子(动态规划)
网友评论