nio基本使用
来源:互联网 发布:伽罗瓦理论知乎 编辑:程序博客网 时间:2024/05/29 12:03
nio速度的提高来自于所使用的结构更接近于操作系统执行I/O的方式:通道和缓冲器。我们可以把它想象成一个煤矿,
通道是一个包含煤层(数据)的矿藏,而缓冲器则是派送到矿藏的卡车。卡车载满煤炭而归,我们再从卡车上获得煤炭。
也就是说,我们并没有直接和通道交互,我们只是和缓冲器交互,并且把缓冲器派送到通道。通道要么从缓冲器获取数据,
要么向缓冲器发送数据。
唯一直接与通道交互的缓冲器是ByteBuffer。还有一个方法选择集,用于以原始的字节形式或基本数据类型输出或读取数据。
但是没有办法输出或读取对象,即使是字符串对象也不行。
旧i/o中的FileInputStream、FileOutputStream以及RandomAccessFile被修改了,可以产生FileChannel(通道)。Reader和
Writer这种字符模式类不能用于产生通道;但是Channels类提供了实用方法,用以在通道中产生Reader和Writer。
实例演示上面三种基本类型的流:
public class GetChannel { private static final int BSIZE=1024; public static void main(String[] args) throws Exception{ FileChannel fc=new FileOutputStream("data.txt").getChannel();//获得通道 fc.write(ByteBuffer.wrap("Some text".getBytes()));//往缓冲器中写数据,并写入通道 fc.close(); fc=new RandomAccessFile("data.txt","rw").getChannel();//获取可读写的通道 fc.position(fc.size());//Move to the end. fc.write(ByteBuffer.wrap("Some more".getBytes())); fc.close(); fc=new FileInputStream("data.txt").getChannel(); ByteBuffer buff=ByteBuffer.allocate(BSIZE);//缓冲区大小 fc.read(buff);//往缓冲器中写入数据 buff.flip();//必须调用缓冲器上的flip(),让它做好让别人读取字节的准备。 while (buff.hasRemaining()){ System.out.print((char)buff.get()); } }}
如果我们打算实用缓冲器执行进一步的read()操作,我们也必须得调用clear()来为每个read()做好准备:
public class ChannelCopy { private static final int BSIZE=1024; public static void main(String[] args) throws Exception{ FileChannel in=new FileInputStream("data.txt").getChannel(), out=new FileOutputStream("data1.txt").getChannel(); ByteBuffer buffer=ByteBuffer.allocate(BSIZE); while (in.read(buffer)!=-1){ buffer.flip();//等待被读取 out.write(buffer); buffer.clear();//等待下一次存入数据 } }}可以用特殊方法transferTo()和transferFrom()将一个通道和另一个通道直接相连:
public class TransferTo { public static void main(String[] args) throws Exception { FileChannel in = new FileInputStream("data.txt").getChannel(), out = new FileOutputStream("data2.txt").getChannel(); in.transferTo(0, in.size(), out); //Or: //out.transferFrom(in,0,in.size()); }}
阅读全文
0 0
- Java NIO基本使用
- Java NIO基本使用
- Nio基本使用
- nio基本使用
- nio基本使用一
- NIO学习二、NIO的基本使用
- java.nio --Path--Files--基本使用
- Nio使用
- NIO基本读写
- NIO的基本应用
- java NIO基本操作
- NIO--01基本介绍
- Tomcat NIO 基本架构
- nio/mina(一) nio基本通信
- NIO--02基本API实现
- NIO的基本的操作
- java.nio NIO原理和使用
- 【NIO】更简单的nio使用方式
- Bat脚本实现定时演示PPT后自动关闭PPT
- idea最后的安装步骤
- dyld: Library not loaded: @rpath/libswiftCore.dylib问题解决
- Kali linux渗透测试(七)
- TCP和UDP的区别和应用
- nio基本使用
- 【知了堂学习笔记】Model1、Model2和MVC架构模式
- poj 1451 难度:中等 字典树+搜索
- 线性表顺序结构增删改查
- STL库中的list的使用和模拟实现
- JS加载与运行
- JVM类加载过程,JDK和JER区别
- log4j学习笔记
- Product of Array Except Self