In the previous article, we introduced the tracking mechanism of the state change inside the buffer, but for the buffer in NiO, there are a lot of content value learning, such as the partition of buffer and data sharing, read-only buffer and so on. In this article we look at some of the more detailed aspects of the buffer.
Allocation of buffers
In the previous examples, we have seen that when creating a buffer object, the static method allocate () is called to specify the capacity of the buffer, in fact calling allocate () is equivalent to creating an array of the specified size and wrapping it as a buffer object. Or we can simply wrap an existing array as a buffer object, as shown in the following example code:
[Java]View PlainCopyprint?
- Public class Bufferwrap {
- public void MyMethod ()
- {
- //Allocate a buffer of the specified size
- Bytebuffer buffer1 = bytebuffer.allocate (10);
- //Wrap an existing array
- byte array[] = new byte[10];
- Bytebuffer buffer2 = bytebuffer.wrap (array);
- }
- }
Buffer shards
In NiO, in addition to allocating or wrapping a buffer object, you can create a sub-buffer based on an existing buffer object, which is a new buffer on the existing buffer, but the existing buffer is data-shared with the created sub-buffer at the level of the underlying array, i.e., The child buffer corresponds to a view window that is an existing buffer. Call the Slice () method to create a sub-buffer, let's take a look at the example:
[Java]View PlainCopy print?
- Import java.nio.*;
- Public class Program {
- static public void Main (String args[]) throws Exception {
- Bytebuffer buffer = bytebuffer.allocate ( 10);
- //data in buffer 0-9
- For (int i=0; i<buffer.capacity (); ++i) {
- Buffer.put ((byte) i);
- }
- //Create sub-buffers
- Buffer.position ( 3);
- Buffer.limit ( 7);
- Bytebuffer slice = Buffer.slice ();
- //Change the contents of the sub-buffer
- For (int i=0; i<slice.capacity (); ++i) {
- byte B = slice.get (i);
- b *= 10;
- Slice.put (i, b);
- }
- Buffer.position ( 0);
- Buffer.limit (Buffer.capacity ());
- While (buffer.remaining () >0) {
- System.out.println (Buffer.get ());
- }
- }
- }
In this example, a buffer with a capacity of 10 is allocated, and data 0-9 is placed in it, and a sub-buffer is created on top of the buffer and the contents of the sub-buffer are changed, and the result of the final output shows that only the sub-buffer "visible" part of the data has changed, And it shows that the sub-buffer is data-shared with the original buffer, and the output is as follows:
Read-only buffer
Read-only buffers are very simple to read, but you cannot write data to them. Any regular buffer can be converted to a read-only buffer by invoking the Asreadonlybuffer () method of the buffer, which returns a buffer that is exactly the same as the original buffer and shares the data with the original buffer, except that it is read-only. If the contents of the original buffer have changed, the contents of the read-only buffer change as well:
[Java]View PlainCopyprint?
- Import java.nio.*;
- Public class Program {
- static public void Main (String args[]) throws Exception {
- Bytebuffer buffer = bytebuffer.allocate ( 10);
- //data in buffer 0-9
- For (int i=0; i<buffer.capacity (); ++i) {
- Buffer.put ((byte) i);
- }
- //Create read-only buffer
- Bytebuffer readonly = Buffer.asreadonlybuffer ();
- //Change the contents of the original buffer
- For (int i=0; i<buffer.capacity (); ++i) {
- byte B = buffer.get (i);
- b *= 10;
- Buffer.put (i, b);
- }
- Readonly.position (0);
- Readonly.limit (Buffer.capacity ());
- the contents of the//read-only buffer are also changed
- While (readonly.remaining () >0) {
- System.out.println (Readonly.get ());
- }
- }
- }
If you attempt to modify the contents of a read-only buffer, the readonlybufferexception exception is reported. Read-only buffers are useful for protecting data. When you pass a buffer to a method of an object, you cannot know whether the method modifies the data in the buffer. Creating a read-only buffer guarantees that the buffer will not be modified. You can only convert a regular buffer to a read-only buffer, and you cannot convert a read-only buffer to a writable buffer.
Direct buffers
A direct buffer is a buffer that allocates memory in a special way to speed up I/O speed, as described in the JDK documentation: given a direct byte buffer, the Java Virtual machine will do its best to perform native I/O operations directly against it. That is, it attempts to avoid copying the contents of the buffer into an intermediate buffer or copying data from an intermediate buffer every time before (or after) the native I/O operation of the underlying operating system is invoked. To allocate a direct buffer, you need to call the Allocatedirect () method instead of the allocate () method, using the same way as a normal buffer, such as the following example of a copy file:
[Java]View PlainCopyprint?
- Import java.io.*;
- Import java.nio.*;
- Import java.nio.channels.*;
- Public class Program {
- static public void Main (String args[]) throws Exception {
- String infile = "C:\\Test.txt";
- FileInputStream fin = new FileInputStream (infile);
- FileChannel fcin = Fin.getchannel ();
- String outfile = String.Format ("C:\\testcopy.txt");
- FileOutputStream fout = new FileOutputStream (outfile);
- FileChannel fcout = Fout.getchannel ();
- //Use Allocatedirect instead of allocate
- Bytebuffer buffer = bytebuffer.allocatedirect ( 1024);
- While (true) {
- Buffer.clear ();
- int r = fcin.read (buffer);
- if (r==-1) {
- Break ;
- }
- Buffer.flip ();
- Fcout.write (buffer);
- }
- }
- }
Memory-mapped file I/O
Memory-mapped file I/O is a way to read and write file data, which can be much faster than regular stream-based or channel-based I/O. Memory-mapped file I/O is done by making the data in the file appear as an array of memory, which at first sounds like just reading the entire file into memory, but in fact it is not. In general, only the portions of the file that are actually read or written are mapped to memory. As the following example code:
[Java]View PlainCopyprint?
- Import java.io.*;
- Import java.nio.*;
- Import java.nio.channels.*;
- Public class Program {
- static private final int start = 0;<span style="font-family:fangsong_gb2312;font-size:13px ;" >
- static private final int size = 1024;
- static public void Main (String args[]) throws Exception {
- Randomaccessfile RAF = new Randomaccessfile ( "C:\\Test.txt", "RW");
- FileChannel FC = Raf.getchannel ();
- Mappedbytebuffer MBB = Fc.map (FileChannel.MapMode.READ_WRITE,
- Start, size);
- Mbb.put ( 0, (byte)97);
- Mbb.put ( 1023, (byte)122);
- Raf.close ();
- }
- }</span>
We have used two articles to introduce the details of the buffer. The more interesting portions of nonblocking I/O in NiO are described in the next article.
Original address: http://blog.csdn.net/wuxianglong/article/details/6612263
Java NIO usage and rationale analysis (c) (EXT)