Java NIO Buffer Learning Notes

Source: Internet
Author: User

Buffer is actually a container object that contains some data to write or just Read. Adding a Buffer object to the NIO reflects an important difference between the new library and the original i/o. In stream-oriented i/o, you write data directly or read the data directly into the stream Object. In the NIO library, all data is processed in a buffer. When the data is read, it is read directly into the Buffer. When the data is written, it is written to the Buffer. Whenever you access data in nio, you put it in a buffer. A buffer is essentially an array. Usually it is a byte array, but you can use other kinds of arrays as Well. But a buffer is more than just an array. Buffers provide structured access to data, and can also track the read/write process of the System. The most commonly used buffer type is Bytebuffer. A bytebuffer can perform get/set operations on its underlying byte array (that is, the acquisition and setting of bytes). Bytebuffer is not the only buffer type in Nio. In fact, there is a buffer type for each of the basic Java types (only The Boolean type does not have its corresponding buffer Class) : Bytebuffercharbuffershortbufferintbufferlongbufferfloatbufferdoublebuffer Each buffer class is an instance of the buffer interface. In addition to bytebuffer, each buffer class has exactly the same operations, except that they handle different types of Data. Because most standard I/O operations use bytebuffer, it has all the shared buffer operations and some unique operations. Let's take a look at the Class-level diagram of buffer: each buffer has the following properties: capacity how much data can be put in this buffer. Capacity is typically specified when buffer is Created. The read and write operation of limit on Buffer cannot cross this Subscript. When writing data into buffer, limit is generally equal to capacity, and when reading the data, the limit represents the length of valid data in Buffer. The positionposition variable tracks how much data is written to the buffer, or how much data is read from the Buffer. rather, when you read data from a channel into a buffer, it indicates which element of the array the next data will be placed IN. For example, If you read three bytes from a channel into a buffer, the Buffer's position will be set to 3, pointing to the 4th element in the Array. conversely, when you get data from a buffer to write a channel, it indicates that the next data is from the Array'sWhich Element. For example, When you write 5 bytes from a buffer into a channel, the Buffer's position is set to 5, which points to the sixth element of the Array. Mark a temporary storage location Subscript. Calling Mark () sets mark to the value of the current position, and subsequent calls to reset () will set the Position property to the value of Mark. Mark's value is always less than or equal to position, and if the value of position is set smaller than mark, the current mark value is Discarded. These properties always meet the following conditions: 0 <= mark <= position <= limit <= the internal implementation mechanism of the buffer: the following is an example of how data is copied from an input channel to an output channel to analyze each variable in detail, and explain how they work together: initial variables: We first observe a newly created buffer, taking Bytebuffer as an example, assuming that the buffer size is 8 bytes, The Bytebuffer initial state is as follows: recall, limit can never be greater than capacity, Both of these values are set to 8 in this Example. We illustrate this by pointing them at the end of the array (8th slot). Let's set the position to 0 again. Indicates that if we read some data into the buffer, then the next read data goes into slot 0. If we write some data from the buffer, the next byte read from the buffer is from slot 0. The position settings are as follows: because the Buffer's maximum data capacity capacity not change, we can ignore it in the discussion below. First Read: Now we can start the read/write operation on the newly created Buffer. first, read some data from the input channel into the Buffer. The first read gets three Bytes. They are placed in the array starting at position, where position is set to 0. After reading, the position is increased to 3, as shown below, the limit does not change. Second read: at the second read, we read the additional two bytes from the input channel into the Buffer. These two bytes are stored in the location specified by position, and position thus increases 2,limit Unchanged. Flip: now we're going to write the data to the output channel. Before we do that, we have to call the flip () method. Its source code is as Follows: public final Buffer flip () {limit = position; position = 0; Mark =-1; return this;} This method does two pieces of non-Often important: I it sets the limit to the current Position. ii It sets the position to 0. The previous figure shows the buffer before the Flip. Here is the buffer after flip: we can now write the data from the buffer to the Channel. Position is set to 0, which means that the next byte we get is the first Byte. The limit has been set to the original position, which means that it includes all the bytes previously read, and a byte is not too many. First write: at the first write, we take four bytes from the buffer and write them to the output channel. This allows the position to increase to 4, while the limit does not change as follows: second write: we have only one byte left to Write. Limit is set to 5 when we call Flip (), and position cannot exceed limit. So the last write operation takes a byte out of the buffer and writes it to the output channel. This allows the position to increase to 5 and keep the limit constant as Follows: clear: The final step is to call the clear () method of the Buffer. This method resets the buffer to receive more Bytes. Its source code is as Follows: public final Buffer clear () {osition = 0; limit = capacity; Mark =-1; return this;} Clear does two very important things: I it sets the limit to the same as Capacity. ii It sets the position to 0. Shows the state of the buffer after the call to clear (), at which time the buffer can now receive new Data. At this point, we just use buffers to transfer data from one channel to another, but programs often need to process data directly. For example, you might want to save user data to Disk. In this case, you must put the data directly into the buffer and then write the buffer to disk with the Channel. or, you may want to read user data from Disk. In this case, you want to read the data from the channel into the buffer, and then examine the data in the Buffer. In fact, each of the basic types of buffers gives us a way to directly access the data in the buffer, and we use Bytebuffer as an example to analyze how to access the data in the buffer directly using its provided get () and put () methods. A) The Get () Bytebuffer class has four get () methods: byte get (); Bytebuffer Get (byte dst[]); Bytebuffer get (byte dst[], int offset, int length); BYTE get (int INDex); The first method gets a single Byte. The second and third methods read a set of bytes into an array. The fourth method gets the bytes from a specific location in the Buffer. Those methods that return Bytebuffer simply return the this value of the buffer that called Them. In addition, we think that the first three get () methods are relative, and the last method is Absolute. Relative means that the get () operation obeys the limit and position values, more specifically, The bytes are read from the current position, and the position is incremented after get. On the other hand, an "absolute" method ignores the limit and position values and does not affect THEM. In fact, it completely bypasses the statistical method of the Buffer. The methods listed above correspond to the Bytebuffer class. Other classes have an equivalent get () method, which, In addition to not processing bytes, is identical in that they deal with types that are compatible with the buffer class. Note: Here we focus on the second and third two methods Bytebuffer get (byte dst[]); Bytebuffer get (byte dst[], int offset, int length); These two get () are used primarily for bulk moving data, which can be used for data replication from buffers to Arrays. The first form only takes an array as an argument, releasing a buffer to the given array. The second form uses the offset and length parameters to specify the sub-range of the target array. The compositing effects of these bulk moves are the same as the loops discussed earlier, but these methods can be much more efficient because the buffer implementation can move data using native code or other Optimizations. Buffer.get (myArray) is equivalent to: buffer.get (myarray,0,myarray.length); note: If the amount of data you require cannot be transmitted, then no data is passed, the state of the buffer remains unchanged, and the Bufferunderflowexception Exception. So when you pass in an array and do not specify a length, you are the equivalent of requiring the entire array to be populated. If the data in the buffer does not fully fill the array, you get an Exception. This means that if you want to pass a small buffer into a large array, you need to explicitly specify the length of data remaining in the Buffer. The first example above does not copy the remaining data elements in the buffer to the bottom of the array, as you did at the first glance. For example, the following code: String str = "com.xiaoluo.nio.MultipartTransfer"; Bytebuffer buffer = Bytebuffer.allocate (50); for (int i = 0; i < str.length (); i++) {buffer.put (str.getbytes () [i]);} buffer.flip (); byte[] buffer2 = new byte[100]; Buffer.get (buffer2); Buffer.get (buffer2, 0, length); System.out.println (new String (buffer2)); This throws the java.nio.BufferUnderflowException exception because the array expects the buffer to fill it up, and if it does, it throws an exception, so the code should change to the following://get the length of the buffer unread data int length = Buffer.remaining (); byte[] buffer2 = new byte[100]; Buffer.get (buffer2, 0, length); b) the put () Bytebuffer class has five put () methods: Bytebuffer put (byte b); Bytebuffer put (byte src[]); Bytebuffer put (byte src[], int offset, int length); Bytebuffer put (bytebuffer src); Bytebuffer put (int index, byte b); The first method writes (put) a single Byte. The second and third methods write a set of bytes from an array. The fourth method writes the data from a given source bytebuffer to this bytebuffer. The Fifth method writes the bytes to a specific location in the Buffer. Those methods that return Bytebuffer simply return the this value of the buffer that called Them. As with the Get () method, we will divide the put () method into "relative" or "absolute". The first four methods are relative, and the fifth method is Absolute. The method shown above corresponds to the Bytebuffer class. Other classes have an equivalent put () method, which is identical except that it is not processing bytes. They deal with types that are compatible with the buffer class. C) the typed get () and put () methods, in addition to the get () and put () methods described in the previous subsections, Bytebuffer are also used to read and write differentOther methods of type value, as Follows: getbyte () getChar () getshort () getInt () getlong () getfloat () getdouble () putbyte () putchar () putshort () Putint () putlong () putfloat () putdouble () in fact, each of these methods has two types: one is relative and the other is Absolute. They are useful for reading formatted binary data (like the header of a file). The following internal loop summarizes the process of using buffers to copy data from an input channel to an output channel. While (true) {//clear method resets the buffer, the new content can be read into buffer buffer.clear (); int val = inchannel.read (buffer); If (val = =-1) {break;}//f The Lip method allows the buffer data to be output to the new channel inside Buffer.flip (); Outchannel.write (buffer); The}read () and write () calls are greatly simplified because many of the work details are done by the Buffer. The clear () and flip () methods are used to toggle the buffer between read and Write. well, the contents of the buffer are written here for the moment, and next we will continue the study of NIO – Channel.

Java NIO Buffer Learning notes

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.