12、NIO、AIO、BIO二
一、NIO2快速读写文件
写完之后记得flush一下,NIO2不能自行创建文件,需要在文件中判断一下。
package com.zxc.L; import org.junit.Test;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List; /**
* Created by Administrator on 2018/2/6 0006.
*/
public class E {
@Test
public void writeFile(){
Path path1= Paths.get("src/com/zxc/L/456.txt"); try {
if(!Files.exists(path1)){
Files.createFile(path1);
}
BufferedWriter bw=Files.newBufferedWriter(path1,StandardCharsets.UTF_8, StandardOpenOption.WRITE);
bw.write("我是谁");
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void readFile(){
Path path1= Paths.get("src/com/zxc/L/456.txt"); try {
List <String>list=Files.readAllLines(path1, StandardCharsets.UTF_8);
for(String s:list){
System.out.println(s);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
二、监听器
记得重置监听器
import java.io.IOException;
import java.nio.file.*; /**
* Created by Administrator on 2018/2/6 0006.
*/
public class F {
public static void main(String[] args) {
try {
WatchService ws= FileSystems.getDefault().newWatchService();
Path path=FileSystems.getDefault().getPath("D://");
WatchKey key=path.register(ws,StandardWatchEventKinds.ENTRY_MODIFY);
boolean shutdown=true;
while(shutdown){
try {
key = ws.take();
for(WatchEvent<?> e:key.pollEvents()){
if (e.kind()==StandardWatchEventKinds.ENTRY_MODIFY){
System.out.println("修改了");
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
key.reset();
shutdown=false;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
三、通道读写
package com.zxc.L; import org.junit.Test; import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption; /**
* Created by Administrator on 2018/2/6 0006.
*/
public class G {
public static void main(String[] args) {
write();
} private static void write() {
Path path1= Paths.get("d://456.txt");
try {
FileChannel fc= FileChannel.open(path1, StandardOpenOption.WRITE);
fc.write(ByteBuffer.wrap("sad".getBytes()));
fc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void read(){
Path path1= Paths.get("d://456.txt");
ByteBuffer buffer=ByteBuffer.allocate(1024);
try {
FileChannel fc= FileChannel.open(path1, StandardOpenOption.READ);
fc.read(buffer,1);
buffer.flip();//使指针返回到缓冲区第一个位置,在读取之前调用。
Charset c=Charset.forName("UTF-8");
System.out.println(c.decode(buffer));
fc.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
四、异步IO读写基础
NIO2的异步能力使用于套接字和文件IO操作,其实异步IO只是一种在读写操作结束前允许进行其他操作的IO处理
java7中有三个新的异步通道:
AsynchronousFileChannel -用于文件IO
AsynchronousSocketChannel -用于套接字IO,支持超时
AsynchronousServerSocketChannel -用于套接字接受异步连接
使用异步API,主要形式:将来式、回调式
将来式:使用java.util.concurrent.Future接口
使用场合:当你希望由主控线程发起IO操作并轮询等到结果时使用将来式异步处理。
1、打开一个AsynchronousFileChannel来读写文件
2、采用了AsynchronousFileChannel,并用Future保存读取结果,所以会自动采用并发IO处理
3、在读取数据时,主线程可以继续执行其他任务。
4、当任务读取完成时,检查数据读取结果。

package com.weikun.A; import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.Future; public class H { public static void main(String[] args) {
// TODO Auto-generated method stub
try {
//1异步打开文件
Path file=Paths.get("g://video//0528///流1.wmv");//找一个比较大的文件
AsynchronousFileChannel channel=AsynchronousFileChannel.open(file);
//2读取1000000字节
ByteBuffer buffer=ByteBuffer.allocate(1024*10); Future<Integer> result=channel.read(buffer, 0);
while(!result.isDone()){//3可以干点别的事情
System.out.println("卫老师");//主线程可以打印些别的
}
Integer bytesRead=result.get();
System.out.println("read:["+bytesRead+"]"); } catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
} }
回调式:匿名内部类中可以分块处理io操作时遇到的情况,并不是向将来式一样可以在io同时主线程做其他的事

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future; public class J {
public static void main(String[] args) throws IOException, InterruptedException, ExecutionException {
Path filePath = Paths.get("1.sql");
AsynchronousFileChannel afc = AsynchronousFileChannel.open(filePath);
ByteBuffer byteBuffer = ByteBuffer.allocate(16 * 1024); //??个数有关
//使用FutureDemo时,请注释掉completionHandlerDemo,反之亦然
//futureDemo(afc, byteBuffer); afc.read(byteBuffer, 0, null, new CompletionHandler<Integer, Object>() {
@Override
public void completed(Integer result, Object attachment) {
System.out.println("Bytes Read = " + result); }
@Override
public void failed(Throwable exc, Object attachment) {
System.out.println(exc.getCause()); }
});
System.out.println("Waiting for completion..."); System.out.println("End");
afc.close();
}
12、NIO、AIO、BIO二的更多相关文章
- NIO,AIO,BIO
同步和异步:同步和异步关注的是消息通信机制, 同步:就是在发出一个“调用”时,在没有得到结果之前,该“调用”就不返回,但是一旦调用返回,就得到返回值了;换句话说:就是由“调用者”主动等待“调用”结果 ...
- BIO NIO AIO 简介
原文: https://github.com/zhongmingmao/nio_demo 简介 NIO与AIO的简单使用 基本概念 同步与异步 同步和异步是针对应用程序和内核的交互而言的:同步指的是用 ...
- IO回忆录之怎样过目不忘(BIO/NIO/AIO/Netty)
有热心的网友加我微信,时不时问我一些技术的或者学习技术的问题.有时候我回微信的时候都是半夜了.但是我很乐意解答他们的问题.因为这些年轻人都是很有上进心的,所以在我心里他们就是很优秀的,我愿意多和努力的 ...
- I/O模型系列之三:IO通信模型BIO NIO AIO
一.传统的BIO 网络编程的基本模型是Client/Server模型,也就是两个进程之间进行相互通信,其中服务端提供位置信息(绑定的IP地址和监听端口),客户端通过连接操作向服务端监听的地址发起连接请 ...
- 【netty】(1)---BIO NIO AIO演变
BIO NIO AIO演变 Netty是一个提供异步事件驱动的网络应用框架,用以快速开发高性能.高可靠的网络服务器和客户端程序.Netty简化了网络程序的开发,是很多框架和公司都在使用的技术. Net ...
- IO复用,AIO,BIO,NIO,同步,异步,阻塞和非阻塞 区别参考
参考https://www.cnblogs.com/aspirant/p/6877350.html?utm_source=itdadao&utm_medium=referral IO复用,AI ...
- java BIO/NIO/AIO 学习
一.了解Unix网络编程5种I/O模型 1.1.阻塞式I/O模型 阻塞I/O(blocking I/O)模型,进程调用recvfrom,其系统调用直到数据报到达且被拷贝到应用进程的缓冲区中或者发生错误 ...
- IO复用,AIO,BIO,NIO,同步,异步,阻塞和非阻塞 区别(百度)
如果面试问到IO操作,这篇文章提到的问题,基本是必问,百度的面试官问我三个问题 (1)什么是NIO(Non-blocked IO),AIO,BIO (2) java IO 与 NIO(New IO)的 ...
- 转载:BIO | NIO | AIO
http://my.oschina.net/bluesky0leon/blog/132361 也谈BIO | NIO | AIO (Java版) 转载自:zheng-lee博客 发布时间: 201 ...
- (转)IO复用,AIO,BIO,NIO,同步,异步,阻塞和非阻塞 区别
本文来自:https://www.cnblogs.com/aspirant/p/6877350.html?utm_source=itdadao&utm_medium=referral,非常感谢 ...
随机推荐
- Linux5355端口被0.0.0.0监听
Linux后台有个systemd-resolv进程,占用5355等端口 博主在一次网络安全加固行动中,netstat -anp发现Linux后台有一个被0.0.0.0监听的端口,5355,显示被sys ...
- android studio2.2 配置NDK
1.配置环境: Android studio2.2 配置NDK NDK版本[android-ndk-r13b-windows-x86_64.zip] NDK下载网址:[https://dl.googl ...
- Ubuntu 安装wps-office
本系列文章由 @YhL_Leo 出品,转载请注明出处. 文章链接: http://blog.csdn.net/yhl_leo/article/details/50288483 本人的ubuntu系统是 ...
- POJ——T1125 Stockbroker Grapevine
http://poj.org/problem?id=1125 Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 36045 ...
- test文件夹,测试类是放在src目录下的,test测试代码是代码啊,当然要放在代码文件夹下
test文件夹,测试类是放在src目录下的,test测试代码是代码啊,当然要放在代码文件夹下 Maven的标准工程结构 Maven的标准工程结构如下: |-- pom.xml(maven的核心配置文件 ...
- ZOJ 3435
求(1,1,1)至(x,y,z)的互质个数. 即求(0,0,0)到(x-1,y-1,z-1)互质个数. 依然如上题那样做.但很慢...好像还有一个分块的思想,得学学. #include <ios ...
- 数据结构与算法系列----最小生成树(Prim算法&Kruskal算法)
一:Prim算法 1.概览 普里姆算法(Prim算法).图论中的一种算法.可在加权连通图里搜索最小生成树.意即由此算法搜索到的边子集所构成的树中.不但包含了连通图里的全部顶点(英语:Ve ...
- 浅析JAVA设计模式之工厂模式(二)
1 工厂方法模式简单介绍 工厂方法 (Factroy Method)模式:又称多态性工厂模式(Polymorphic Factory),在这样的模式中,核心工厂不再是一个详细的类.而是一个抽象工厂,提 ...
- bzoj3275: Number(最小割)
3275: Number 题目:传送门 题解: 双倍经验@bzoj3158 代码: #include<cstdio> #include<cstring> #include< ...
- Stop being a perfectionist
节选自 7 Things You Need To Stop Doing To Be More Productive, Backed By Science “We found that perfecti ...