首页 技术 正文
技术 2022年11月11日
0 收藏 452 点赞 3,132 浏览 1630 个字

参考 http://wenku.baidu.com/link?url=rq-BEp3Et4JRrE62f2Lv9hq8nT_Gq0XPb65h8OBqTAt-ILfqKmdjIhVEp8bctIdm0uqWJG6P_U0-B8gYSjSEUGgmEwmiQIKobcGxvBM3YsG

nio是非阻塞io,nio 可以理解为new io,也可以理解为net+io,所以,我们探讨一下非阻塞io的过程。

1.channel是通道,是对原来的流的模拟,可以实现同时读写,双向性。而流呢,我们知道inputstream outputstream 只能进行单项读写。

2,缓冲区,其实就是数组,byte数组,int数组,等类型,以往是阻塞的,流的处理,此处引入缓冲区,无论读写文件,网络流,都要从缓冲区读写。

 import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel; //这个例子是文件IO,中传统IO和NIO的例子
public class NIO学习 {
public static void ioRead(File f) throws IOException
{
FileInputStream fin=new FileInputStream(f);
byte[] b=new byte[1024];
fin.read(b);
System.out.println(new String(b)); }
public static void nioRead(File f) throws IOException
{ FileInputStream fin=new FileInputStream(f);
FileChannel channal=fin.getChannel();
ByteBuffer by=ByteBuffer.allocate(1024);
channal.read(by);
byte n[]=by.array();
System.out.println(new String(n)); }
public static void copyFile(File f1,File f2) throws IOException
{
//获得源文件的输入流
FileInputStream input=new FileInputStream(f1);
//获得文件的输入流
FileOutputStream output=new FileOutputStream(f2); //获得channel
FileChannel cinput=input.getChannel();
FileChannel coutput=output.getChannel(); //缓存的设置
ByteBuffer by=ByteBuffer.allocate(1024); while(true)
{
by.clear(); //postion=0,limit=capacity
int r=cinput.read(by);
if(r==-1) break;
by.flip();
coutput.write(by); } } /**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File f1=new File("E:\\test\\source.txt");
File f2=new File("E:\\test\\dest.txt");
copyFile(f1,f2);
// ioRead(f1);
nioRead(f2);
} }
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,487
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,903
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,736
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,486
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,126
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,287