Java IO and NIO Problems

Source: Internet
Author: User

Stream is the earliest Java abstraction of IO, while Channel is NIO's abstraction of IO for new Java. 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. The basic unit of the stream and channel is byte, but the stream uses byte array as the buffer intermediary, while the channel uses ByteBuffer as the buffer intermediary.
The Bytes contained in a stream are the same as the stream. Once the stream passes, it cannot be used any more. However, because the stream is implemented as an abstract class, you can override some operations of the parent class in its subclass. Therefore, the input/output stream of the subclass may have additional control operations, this allows you to re-read part of the stream content, such as the mark and reset Functions of the stream. However, not every stream has these two functions, you can use the markSupported method to determine whether the tag function is supported. Because the stream cannot be reused, what if a stream has multiple receivers? The tag and reset functions described above are one of the methods. You can also save all the data in the stream to a byte array, in different acceptance processes, data transmission is completed through this byte array, rather than using stream objects. The stream tag and reset function is also implemented through the second method, but the storage and operation of this byte array is implemented by some sub-classes of the stream, such as BufferedInputStream.
When calling the stream's read method, if there is not enough data to use, the read method will be blocked until the current stream is successfully prepared. The data read from the stream does not immediately enter the Target media, but is first placed into a byte array and other buffers, and the appropriate time before the actual write operation. Of course, you can force write by calling the flush method. Note that when the buffer is full or the stream is closed, the actual write operation is automatically executed.
Byte streams process bytes, and Java IO also processes character streams, that is, java. io. reader class and java. io. writer class and its subclass. character classes are generally created through the byte stream InputStream class and OutputStream class. They correspond to the InputStreamReader class and OutputStreamWriter class. You only need to specify the encoding format.

The basic buffer used by the Java NIO channel is ByteBuffer, where three basic state variables are: capacity (capacity), which is the buffer size; read/write restrictions (limit ), the maximum position allowed for read/write in the total size. The position indicates the current read/write position. These three state variables are in bytes. For example, if it is CharBuffer, it is in character units, IntBuffer is in integer units, and so on.
The basic method of ByteBuffer: clear, set the read/write limit to the buffer capacity, and set the read/write location to 0. The flip method sets the read/write limit to the current read/write location, at the same time, set the read/write location to 0, rewind method, and set the read/write location to 0, and compact method without changing the read/write limit, copy the data from the current read/write location to the beginning of the internal bucket, and then move the read/write location to the next location of the copied data, the read/write limit is set to the capacity. The implementation of ByteBuffer can be divided into direct buffer and non-direct buffer. The direct buffer is directly completed using the underlying IO operations of the operating system, improving the performance of read/write operations, however, it also brings an extra cost for creation and destruction. The direct buffer is usually resident memory, which increases the memory overhead and is generally used in High Performance situations. The following uses three simple examples to understand the operations of the stream and channel on file replication.
[Java]
// Use stream to copy objects
Public static void copyFileByStream (String src, String dest) throws IOException {
FileInputStream in = new FileInputStream (src );
File file = new File (dest );
If (! File. exists ())
File. createNewFile ();
FileOutputStream out = new FileOutputStream (file );
Int c;
Byte buffer [] = new byte [1024]; // The number of bytes read each time
While (c = in. read (buffer ))! =-1 ){
Out. write (buffer );
}
In. close ();
Out. close ();
}
// Use ByteBuffer as the buffer for File Replication
Public static void copyFileByByteBuffer (String src, String dest) throws IOException {
ByteBuffer buffer = ByteBuffer. allocateDirect (32*1024); // allocate the size of ByteBuffer
FileInputStream in = new FileInputStream (src );
FileOutputStream out = new FileOutputStream (dest );
FileChannel s = in. getChannel ();
FileChannel d = out. getChannel ();
While (s. read (buffer)> 0 | buffer. position ()! = 0) {// The ByteBuffer is used for transmission in the channel, so you do not need to record the actual number of bytes read each time.
Buffer. flip ();
D. write (buffer );
Buffer. compact ();
}
 
}
 
// Use the channel transmission method to copy files
Public static void copyFileByChannelTransfer (String src, String dest) throws IOException {
ByteBuffer buffer = ByteBuffer. allocateDirect (32*1024 );
FileInputStream in = new FileInputStream (src );
FileOutputStream out = new FileOutputStream (dest );
FileChannel s = in. getChannel ();
FileChannel d = out. getChannel ();
S. transferTo (0, s. size (), d); // transmits data from one channel to another.

}
As can be seen from the above, the ByteBuffer class does not need to record the actual number of bytes read each time, as long as a fixed size ByteBuffer is allocated, the file channel's transferTo method simplifies data transmission.
Operations on large files generally use the ByteBuffer subclass MappedByteBuffer, which maps the system's memory address to the file to be operated. Operations on these memory addresses are equivalent to reading the file content, this greatly improves the performance of the operating file. For detailed usage, see the relevant documentation.
The FileChannel class also supports the lock and tryLock methods to lock files, but the lock is at the virtual machine level. For multi-thread programs on virtual machines, this locking mechanism cannot be used to coordinate different threads to access files. The lock of the FileChannel class is the lock between the application and the application.
Because the methods provided in traditional Socket and ServerSocket classes related to establishing connections and data transmission are both blocking, Socket channels provide non-blocking and multiplexing Socket connections. Multiplexing sockets require a Selector to manage and listen to all socket channels. When some socket channels have events of interest to Selector, this channel becomes available, and various channel operations can be performed. But at the beginning, we need to register the socket channel we need to listen to on the Selector to indicate that we need the Selector to listen to this socket channel.
There is a good metaphor on the Internet to describe socket blocking and non-blocking methods. The excerpt is as follows:
A bus from A to B may get off at many points on the road. The driver does not know which persons will get off the bus. What should they do better?
1. The driver regularly asks if each passenger has arrived at the destination. If someone says so, the driver stops and gets off the bus. (Similar to blocking)
2. each person (equivalent to socket channel) tells the conductor (equivalent to Selector) his destination (equivalent to a socket event), then goes to bed, and the driver (equivalent to CPU) only interacts with the conductor, at a certain point, the conductor notifies the passengers to get off the bus. (Similar to non-blocking), it is clear that each person to reach a destination can be considered as a thread, and the driver can be considered as a CPU. In the blocking mode, each thread needs to continuously poll and switch the context to locate the destination. In the non-blocking mode, every passenger (thread) is sleeping (sleep) and wakes up only when the real external environment is ready. Such a wake-up will certainly not be blocked.


 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.