Read and Write java-16.4 nio from the ground up (ByteBuffer usage)
In this chapter, we will discuss the reading and writing of nio.
1. Read 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();}}
Process Diagram: (reference from http://www.iteye.com/magazines/132-Java-NIO)
Data Reading Process:
(1) nio does not directly output the stream as io, but first establishes a data pipeline.
(2) nio interacts with each other through a buffer, instead of directly reading the stream.
(3) The number in ByteBuffer. allocate (48) determines the size of data stored in the cache.
(4) When calling buf. flip (), first read the data to the Buffer, then reverse the Buffer, and then read the data from the Buffer.
(5) If you break a breakpoint on the output statement, you can find a special phenomenon. Its output is an English character, and the output is the same as that of typing.
2. Write 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();}}
Data Writing Process:
(1) nio does not directly input a stream as io, but first establishes a data pipeline.
(2) nio interacts with each other through a buffer, instead of Directly Writing streams.
(3) Use ByteBuffer. wrap to write data to the cache. Because the cache only accepts binary data, you need to convert the data format
(4) Transfer Data in the cache to a file through a channel
Summary: This chapter describes the process of reading and writing nio.