一、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. jquery中的jsonp跨域调用

                                                    jquery jsonp跨域调用接口

  2. React:关于虚拟DOM(Virtual DOM)

    Virtual DOM 是一个模拟 DOM 树的 JavaScript 对象. React 使用 Virtual DOM 来渲染 UI,当组件状态 state 有更改的时候,React 会自动调用组件 ...

  3. js本地对象——Date()

    Date()是JavaScript的本地对象,用于获取当前的时间,包括年.月.日.时.分.秒,可以精确到毫秒级:该对象返回的是UTC 协调世界时(Coordinated Universal Time) ...

  4. WinServer-IIS-js无法加载问题

    IIS中无法加载JS文件错误 尝试下面的几种解决方法,一起用

  5. angular-resource

    上一篇中讲到使用$http同服务器进行通信,但是功能上比较简单,angularjs还提供了另外一个可选的服务$resource,使用它可以非常方便的同支持restful的服务单进行数据交互. 安装 n ...

  6. MySQL高可用系列之MHA(二)

    一.參数说明 MHA提供了一系列配置參数.深入理解每一个參数的详细含义,对优化配置.合理使用MHA非常重要.非常多高可用性也都是通过合理配置一些參数而实现的. MHA包含例如以下配置參数,分别说明例如 ...

  7. Android TextView 横向滚动(跑马灯效果)

    Android TextView 中当文字比較多时希望它横向滚动显示,以下是一种亲測可行的方法. 效果图: 1.自己定义TextView,重写isFocused()方法返回true,让自己定义Text ...

  8. QMutex“A mutex must be unlocked in the same thread that locked it”解决(在run里创建对象是不二法宝)

    多线程时出现如下警告信息: A mutex must be unlocked in the same thread that locked it: 原因可能有二: 1.创建QMutex不在当前线程: ...

  9. Oracle RAC集群体系结构

    一. Oracle集群体系结构 Oracle RAC,全称是Oracle Real Application Cluster,即真正的应用集群,是oracle提供的一个并行集群系统,整个集群系统由Ora ...

  10. Codeforces 987C. Three displays(o(n^2))

    刚开始三重循环tle test11.后来想了个双重循环的方法. 解题思路: 1.双重循环一次,用一个一位数组存j和比j小的i的和的最小值. 2.再双重循环一次,找到比j大的数k,更新结果为ans=mi ...