◆ Input/output: Conceptual description
I/O Introduction
I/O? Or input/output? It refers to the interface between the computer and the external world or between a program and the rest of the computer. It is critical to any computer system, so all I/O entities are actually built in the operating system. A separate program generally allows the system to do most of the work for them.
In Java programming, I/O has been completed using the stream method until recently. All I/O operations are regarded as the movement of a single byte, and one byte is moved at a time through an object called Stream. Stream I/O is used to contact the external world. It is also used internally to convert an object into bytes and then convert it back to an object.
NIO has the same effect and purpose as the original I/O, but does it use different methods? Block I/O. As you will learn in this tutorial, block I/O efficiency can be much higher than stream I/O efficiency.
Why NIO?
NIO is created to enable Java programmers to achieve high-speed I/O without writing custom local code. NIO transfers the most time-consuming I/O operations (that is, the filling and extraction buffer) back to the operating system, thus greatly improving the speed.
Stream and block comparison
The most important difference between the original I/O Library (in java. io. *) and NIO is data packaging and transmission. As mentioned above, the original I/O processes data in a stream, while NIO processes data in blocks.
Stream-oriented I/O systems process data in one byte at a time. An input stream generates one byte of data, and an output stream consumes one byte of data. It is very easy to create filters for streaming data. It is relatively simple to link several filters so that each filter is only responsible for one part of a single complex processing mechanism. The disadvantage is that stream-oriented I/O is usually quite slow.
A block-oriented I/O system processes data in blocks. Each operation generates or consumes a data block in one step. Processing Data by block is much faster than processing data by (streaming) bytes. However, block-oriented I/O lacks the elegance and simplicity of stream-oriented I/O.
Integrated I/O
In JDK 1.4, the original I/O package and NIO have been well integrated. Java. io. * has been re-implemented based on NIO, so now it can take advantage of some NIO features. For example, some classes in the java. io. * package contain methods for reading and writing data in the form of blocks, which makes processing faster even in a more stream-oriented system.
You can also use the NIO library to implement standard I/O functions. For example, you can easily use block I/O to move data one byte at a time. However, as you can see, NIO also provides many benefits not found in the original I/O package.
◆ Channels and Buffers
Overview
Channels and buffers are the core objects in NIO. They are used in almost every I/O operation.
The channel simulates the streams in the original I/O package. All data to any destination (or from any place) must pass through a Channel object. A Buffer is essentially a container object. All objects sent to a channel must first be placed in the buffer zone. Similarly, any data read from the channel must be read to the buffer zone.
In this section, you will learn how NIO channels and buffers work.
What is a buffer?
Buffer is an object that contains data to be written or read. Adding a Buffer object to NIO reflects an important difference between the new library and the original I/O. In Stream-oriented I/O, you can directly write data or directly read the data to the Stream object.
In the NIO database, all data is processed using a buffer. When reading data, it is directly read into the buffer. When writing data, it is written to the buffer. When you access the data in NIO at any time, you put it in the buffer zone.
The buffer is essentially an array. It is usually a byte array, but other types of arrays can also be used. However, a buffer zone is not just an array. The buffer zone provides structured access to data, and supports tracking system read/write processes.
Buffer type
The most common buffer type is ByteBuffer. A ByteBuffer can perform get/set operations on its underlying byte array (that is, obtaining and setting byte ).
ByteBuffer is not the only buffer type in NIO. In fact, each basic Java type has a buffer type:
• ByteBuffer
• CharBuffer
• Protocol Buffer
• IntBuffer
• LongBuffer
• FloatBuffer
• DoubleBuffer
Each Buffer class is an instance of the Buffer interface. Except for ByteBuffer, each Buffer class has identical operations, but they process different data types. Because most standard I/O operations use ByteBuffer, it has all the shared buffer operations and some special operations.
Now you can take a moment to run UseFloatBuffer. java, which contains an application example of a typed buffer.
What is a channel?
A Channel is an object that can be used to read and write data. Compare nio with the original I/O, and the channel is like a stream.
As mentioned above, all data is processed through the Buffer object. You will never write bytes directly into the channel. Instead, you write data to a buffer that contains one or more bytes. Similarly, you will not directly read the byte from the channel, but read the data from the channel into the buffer zone and then get the byte from the buffer zone.
Channel Type
The difference between a channel and a stream is that the channel is bidirectional. The stream only moves in one direction (a stream must be an InputStream or a subclass of OutputStream), and the channel can be used for reading, writing, or reading and writing at the same time.
Because they are bidirectional, the channel can better reflect the real situation of the underlying operating system than the stream. In the UNIX model, the underlying operating system channel is bidirectional.
◆ From theory to practice: Reading and Writing in NIO
Overview
Reading and writing are the basic processes of I/O. Reading from a channel is simple: you only need to create a buffer, and then let the channel read data into the buffer. Writing is also quite simple: create a buffer, fill it with data, and then let the channel use the data for writing.
In this section, we will learn some knowledge about reading and writing data in Java programs. We will review NIO's main components (buffers, channels, and some related methods) to see how they interact for read/write. In the following sections, we will analyze each component and its interaction in more detail.
Read from File
In our first exercise, we will read some data from a file. If you use the original I/O, you only need to create a FileInputStream and read it from it. In NIO, the situation is slightly different: We first get a FileInputStream object from FileInputStream, and then use this channel to read data.
In the NIO system, you read data from the channel at any time, but you do not read data directly from the channel. Because all the data eventually resides in the buffer, you read it from the channel.
Therefore, reading a file involves three steps: (1) getting a Channel from FileInputStream, (2) creating a Buffer, and (3) reading data from a Channel to a Buffer.
Now let's take a look at this process.
Three easy steps
The first step is to obtain the channel. We get the channel from FileInputStream:
Copy codeThe Code is as follows: FileInputStream fin = new FileInputStream ("readandshow.txt ");
FileChannel fc = fin. getChannel ();
The next step is to create a buffer:Copy codeThe Code is as follows: ByteBuffer buffer = ByteBuffer. allocate (1024 );
Finally, you need to read data from the channel to the buffer, as shown below:Copy codeThe Code is as follows: fc. read (buffer );
You will notice that we do not need to tell the channel how much data to read into the buffer zone. Each buffer zone has a complex internal statistical mechanism that tracks how much data has been read and how much space can accommodate more data.
Write files
Writing a file to NIO is similar to reading from a file. First, obtain a channel from FileOutputStream:Copy codeThe Code is as follows: FileOutputStream fout = new FileOutputStream ("writesomebytes.txt ");
FileChannel fc = fout. getChannel ();
The next step is to create a buffer and put some data in it-here, the data will be taken from an array named message, this array contains the ASCII bytes of the string "Some bytes" (buffer will be explained later in this tutorial. flip () and buffer. put () call ).Copy codeThe Code is as follows: ByteBuffer buffer = ByteBuffer. allocate (1024 );
For (int I = 0; I
Buffer. put (message [I]);
}
Buffer. flip ();
The last step is to write data into the buffer.Copy codeThe Code is as follows: fc. write (buffer );
Note that you do not need to tell the channel to write multiple data here. The internal statistical mechanism of the buffer zone tracks how much data it contains and how much data it needs to write.
Read/write Integration
Next, let's take a look at what happens when reading and writing are integrated. We use a simple program named CopyFile. java as the basis for this exercise. It copies all the content of a file to another file. CopyFile. java executes three basic operations: first create a Buffer, then read the data from the source file to the Buffer, and then write the Buffer to the target file. This program repeats-read, write, read, and write-until the source file ends.
The CopyFile program shows you how to check the operation status and how to reset the buffer using the clear () and flip () methods, prepare a buffer to write the newly read data to another channel.
Example of running CopyFile
Because the buffer zone tracks its own data, the inner loop of the CopyFile program is very simple, as shown below:Copy codeThe Code is as follows: fcin. read (buffer );
Fcout. write (buffer );
The first row reads data from the input channel fcin into the buffer, and the second row writes the data to the output channel fcout.
Check status
The next step is to check when the copy is completed. If there is no more data, the copy operation is complete, and the read () method returns-1 to determine this, as shown below:Copy codeThe Code is as follows: int r = fcin. read (buffer );
If (r =-1 ){
Break;
}
Reset the buffer
Finally, we call the clear () method before reading the buffer from the input channel. Similarly, before writing the buffer to the output channel, we call the flip () method as follows:Copy codeThe Code is as follows: buffer. clear (); int r = fcin. read (buffer );
If (r =-1 ){
Break;
}
Buffer. flip ();
Fcout. write (buffer );
The clear () method resets the buffer so that it can accept the read data. The flip () method allows the buffer zone to write the newly read data to another channel.