Detailed usage of java.nio.Buffer flip() method

 

Today, when I was reading Java programming ideas, I encountered the java.nio.Buffer flip() method. I didn't understand what it was used for, so I quickly checked the Chinese API. The above translation of the API is: "reverse this buffer. First set a limit on the current location, and then set the location to zero. If a tag has been defined, discard the tag.";  

To tell you the truth, after reading it several times, I really don't understand what it means, so I checked the English API. It says: Flips this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded. The meaning is roughly like this: change the current position of the buffer, And set the current position to 0. What this means is: set the pointer of the cache byte array to the start sequence of the array, that is, the array subscript 0. In this way, you can traverse (read) the buffer from the beginning of the buffer.  

The flip method in buffer involves the concepts of Capacity,Position and limit in buffer. Capacity is fixed in the read-write mode, which is the buffer size we allocate. Position is similar to the read-write pointer, indicating the current read (write) location. Limit indicates the maximum amount of data that can be written in the write mode. At this time, it is the same as capacity. In the read mode, it indicates the maximum amount of data that can be read. At this time, it is the same as the actual data size in the cache. When the flip method is called in the write mode, the limit is set to the current value of position (that is, how much data is currently written), and the position will be set to 0 to indicate that the read operation starts from the head of the cache. That is, after the flip is called, the read / write pointer refers to the cache header, and the maximum length of the previously written data can only be read (not the capacity of the entire cache).
  
    Example code (code borrowed from Java programming idea P552):  

  

 1 package cn.com.newcom.ch18;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.FileOutputStream;
 5 import java.io.RandomAccessFile;
 6 import java.nio.ByteBuffer;
 7 import java.nio.channels.FileChannel;
 8 
 9 /**
10  * Get channel
11  * 
12  * @author zhq
13  * 
14  */
15 public class GetChannel {
16     private static final int SIZE = 1024;
17 
18     public static void main(String[] args) throws Exception {
19         // Gets the channel that allows write operations
20         FileChannel fc = new FileOutputStream("data.txt").getChannel();
21         // Wrap byte arrays into buffers
22         fc.write(ByteBuffer.wrap("Some text".getBytes()));
23         // Close channel
24         fc.close();
25 
26         // Pipeline created by random read-write file stream
27         fc = new RandomAccessFile("data.txt", "rw").getChannel();
28         // fc.position() calculates the number of bytes from the beginning of the file to the current position
29         System.out.println("File location for this channel:" + fc.position());
30         // Set the file location of this channel, fc.size() the current size of the file of this channel. After this statement is executed, the channel location is at the end of the file
31         fc.position(fc.size());
32         // Writes bytes at the end of the file
33         fc.write(ByteBuffer.wrap("Some more".getBytes()));
34         fc.close();
35 
36         // Read file with channel
37         fc = new FileInputStream("data.txt").getChannel();
38         ByteBuffer buffer = ByteBuffer.allocate(SIZE);
39         // Reads the contents of the file into the specified buffer
40         fc.read(buffer);
41         buffer.flip();//This line statement must have
42         while (buffer.hasRemaining()) {
43             System.out.print((char)buffer.get());
44         }
45                   fc.close();
46     }
47 }

Note: buffer.flip(); There must be. If not, it is read from the end of the file. Of course, all the characters read are characters when byte=0. Through buffer.flip(); With this statement, you can change the current location of the buffer to the first location of the buffer.

 
Classification:   Java
 
 
_________________________________________________________________________________

The hasRemaining() method of the java.nio.Buffer class is used to determine whether there are any elements between the current position and the limit.

Usage:

public final boolean hasRemaining()

Return value: this method returns true if and only if at least one element is left in this buffer.


The following is an example illustrating the hasRemaining() method:

Example 1:

// Java program to demonstrate 
// hasRemaining() method 
  
import java.nio.*; 
import java.util.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Declaring the capacity of the ByteBuffer 
        int capacity = 10; 
  
        // creating object of bytebuffer 
        // and allocating size capacity 
        ByteBuffer bb = ByteBuffer.allocate(capacity); 
  
        // putting the value in bytebuffer 
        bb.put((byte)10); 
        bb.put((byte)20); 
        bb.rewind(); 
  
        // Typecast bytebuffer to Buffer 
        Buffer buffer = (Buffer)bb; 
  
        // checking buffer is backed by array or not 
        boolean isRemain = buffer.hasRemaining(); 
  
        // checking if else condition 
        if (isRemain) 
            System.out.println("there is at least one "
                               + "element remaining "
                               + "in this buffer"); 
        else
            System.out.println("there is no "
                               + "element remaining "
                               + "in this buffer"); 
    } 
}
 
Output:
there is at least one element remaining in this buffer

Example 2:

// Java program to demonstrate 
// hasRemaining() method 
  
import java.nio.*; 
import java.util.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
  
        // Declaring the capacity of the ByteBuffer 
        int capacity = 0; 
  
        // creating object of bytebuffer 
        // and allocating size capacity 
        ByteBuffer bb = ByteBuffer.allocate(capacity); 
  
        // Typecast bytebuffer to Buffer 
        Buffer buffer = (Buffer)bb; 
  
        // checking buffer is backed by array or not 
        boolean isRemain = buffer.hasRemaining(); 
  
        // checking if else condition 
        if (isRemain) 
            System.out.println("there is at least one "
                               + "element remaining"
                               + " in this buffer"); 
        else
            System.out.println("there is no "
                               + "element remaining"
                               + " in this buffer"); 
    } 
}
 
Output:
there is no element remaining in this buffer

reference resources:   https://docs.oracle.com/javase/9/docs/api/java/nio/Buffer.html#hasRemaining-

 
 

Keywords: Java

Added by VagabondKites on Sat, 04 Dec 2021 01:01:21 +0200