从头认识java-16.4 nio的读与写(ByteBuffer的使用)

来源:互联网 发布:wap手机网站源码 编辑:程序博客网 时间:2024/05/09 23:07

这一章节我们来讨论一下nio的读与写。

1.nio的读

package com.ray.ch16;import java.io.IOException;import java.io.RandomAccessFile;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;public class Test {public static void main(String[] args) throws IOException {RandomAccessFile aFile = new RandomAccessFile("d://fg.ini", "rw");FileChannel inChannel = aFile.getChannel();ByteBuffer buf = ByteBuffer.allocate(48);int bytesRead = inChannel.read(buf);while (bytesRead != -1) {buf.flip();while (buf.hasRemaining()) {System.out.print((char) buf.get());}buf.clear();bytesRead = inChannel.read(buf);}aFile.close();}}


过程图:(引用自http://www.iteye.com/magazines/132-Java-NIO)


数据读取的过程:

(1)nio不像io那样直接输出流,而是先建立输送数据的管道

(2)nio通过一个buffer缓存器来进行交互,而不再是直接读取流

(3)ByteBuffer.allocate(48)里面的数字决定缓存器的存储数据大小

(4)buf.flip() 的调用,首先读取数据到Buffer,然后反转Buffer,接着再从Buffer中读取数据。

(5)如果你断点在输出语句上面,就可以发现一个比较特别的现象,它的输出是一个一个英文字符,像打字一样的输出



2.nio的写

package com.ray.ch16;import java.io.IOException;import java.io.RandomAccessFile;import java.nio.ByteBuffer;import java.nio.channels.FileChannel;public class Test {public static void main(String[] args) throws IOException {RandomAccessFile aFile = new RandomAccessFile("d://123.txt", "rw");FileChannel inChannel = aFile.getChannel();ByteBuffer buf = ByteBuffer.wrap("hello world tttttttttttttt".getBytes());inChannel.write(buf);buf.clear();inChannel.close();aFile.close();}}


数据写入的过程:

(1)nio不像io那样直接输入流,而是先建立输送数据的管道

(2)nio通过一个buffer缓存器来进行交互,而不再是直接写入流

(3)使用ByteBuffer.wrap写入缓存器,由于缓存器只接受二进制数据,因此需要把里面的数据转换格式

(4)通过通道,把缓存器里面的数据输送到文件里面


总结:这一章节主要介绍了nio的读与写的过程。


这一章节就到这里,谢谢。

-----------------------------------

目录



0 0
原创粉丝点击