一、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二的更多相关文章

  1. NIO,AIO,BIO

    同步和异步:同步和异步关注的是消息通信机制, 同步:就是在发出一个“调用”时,在没有得到结果之前,该“调用”就不返回,但是一旦调用返回,就得到返回值了;换句话说:就是由“调用者”主动等待“调用”结果 ...

  2. BIO NIO AIO 简介

    原文: https://github.com/zhongmingmao/nio_demo 简介 NIO与AIO的简单使用 基本概念 同步与异步 同步和异步是针对应用程序和内核的交互而言的:同步指的是用 ...

  3. IO回忆录之怎样过目不忘(BIO/NIO/AIO/Netty)

    有热心的网友加我微信,时不时问我一些技术的或者学习技术的问题.有时候我回微信的时候都是半夜了.但是我很乐意解答他们的问题.因为这些年轻人都是很有上进心的,所以在我心里他们就是很优秀的,我愿意多和努力的 ...

  4. I/O模型系列之三:IO通信模型BIO NIO AIO

    一.传统的BIO 网络编程的基本模型是Client/Server模型,也就是两个进程之间进行相互通信,其中服务端提供位置信息(绑定的IP地址和监听端口),客户端通过连接操作向服务端监听的地址发起连接请 ...

  5. 【netty】(1)---BIO NIO AIO演变

    BIO NIO AIO演变 Netty是一个提供异步事件驱动的网络应用框架,用以快速开发高性能.高可靠的网络服务器和客户端程序.Netty简化了网络程序的开发,是很多框架和公司都在使用的技术. Net ...

  6. IO复用,AIO,BIO,NIO,同步,异步,阻塞和非阻塞 区别参考

    参考https://www.cnblogs.com/aspirant/p/6877350.html?utm_source=itdadao&utm_medium=referral IO复用,AI ...

  7. java BIO/NIO/AIO 学习

    一.了解Unix网络编程5种I/O模型 1.1.阻塞式I/O模型 阻塞I/O(blocking I/O)模型,进程调用recvfrom,其系统调用直到数据报到达且被拷贝到应用进程的缓冲区中或者发生错误 ...

  8. IO复用,AIO,BIO,NIO,同步,异步,阻塞和非阻塞 区别(百度)

    如果面试问到IO操作,这篇文章提到的问题,基本是必问,百度的面试官问我三个问题 (1)什么是NIO(Non-blocked IO),AIO,BIO (2) java IO 与 NIO(New IO)的 ...

  9. 转载:BIO | NIO | AIO

    http://my.oschina.net/bluesky0leon/blog/132361 也谈BIO | NIO | AIO (Java版)   转载自:zheng-lee博客 发布时间: 201 ...

  10. (转)IO复用,AIO,BIO,NIO,同步,异步,阻塞和非阻塞 区别

    本文来自:https://www.cnblogs.com/aspirant/p/6877350.html?utm_source=itdadao&utm_medium=referral,非常感谢 ...

随机推荐

  1. visual studio 2017 使用码云gitee进行源代码管理

    在码云新建项目 复制项目地址 visual studio  操作 新建项目 提交到码云

  2. url中jsessionid的理解

    (1) 这是一个保险措施 因为Session默认是需要Cookie支持的 但有些客户浏览器是关闭Cookie的 这个时候就需要在URL中指定服务器上的session标识,也就是5F4771183629 ...

  3. ASP.NET-前台view返回model集合

    有时操作列表的时候想一次提交一个model集合,这样后台controller直接接受后就可以直接进行操作了,不用使用js,比较方便,也体现了MVC的Binding模式的优势,方法如下: 准备: 1.两 ...

  4. cogs 2170. 大整数取模

    2170. 大整数取模 ★   输入文件:bigint.in   输出文件:bigint.out   简单对比时间限制:1 s   内存限制:256 MB [题目描述] 输入正整数n和m,输出n mo ...

  5. HDU 1796

    呃,我竟然傻了,同时被a且b整除的个数为n/(a*b). 其实应该是n/[a,b]才对,是他们的最小公倍数啊... #include <iostream> #include <cst ...

  6. c#将List&lt;T&gt;转换成DataSet

    /// <summary>         /// List<T> 转换成DataSet         /// </summary>         /// &l ...

  7. httputil用http获取请求的工具类

    package com.xiaocan.demo.util; import java.io.IOException; import java.io.InputStream; import java.u ...

  8. [JZOJ5166] [NOIP2017模拟6.26卢学魔] 解题报告 (记忆化搜索|拓扑排序)

    题目链接: http://172.16.0.132/senior/#main/show/5166 题目: 题解: 这个没什么好讲的,就是注意生产者没人吃也不是食物链,这告诉我们要积累生物知识注意细节 ...

  9. Ubuntu下使用Deepin-wine的移植版安装qq微信等

    title: Ubuntu下使用Deepin-wine的移植版安装qq微信等 toc: false date: 2018-09-18 16:12:49 categories: methods tags ...

  10. (转载)自定义View——弹性滑动

    滑动是Android开发中非常重要的UI效果,几乎所有应用都包含了滑动效果,而本文将对滑动的使用以及原理进行介绍. 一.scrollTo与ScrollBy View提供了专门的方法用于实现滑动效果,分 ...