Java examples on java.nio
- How do I use a FileChannel to read data into a Buffer?
- How do I read all lines from a file?
- How do I copy one file to another file?
- How do I write data into Buffer using put method?
- How do I clear a buffer using clear method?
- How do I create a NIO Buffer?
- How do I read data from a buffer into channel?
- How do I clear a buffer using compact method?
- How do I change the buffer mode between write and read?
- How do I reread the content of a buffer?
- How do I copy a file in JDK 7?
- How do I write a text file in JDK 7?
- How do I get file basic attributes?
- How do I set file last modified time?
- How do I set the value of file attributes?
- How do I use the DosFileAttributes class?
- How to get some information about Path object?
- How do I remove redundant elements from a Path?
- How do I create and delete a file in JDK 7?
- How do I find files in a directory using DirectoryStream?
- How do I create a java.nio.Path?
- How to recursively list all text files in a directory?
- How to monitor file or directory changes?
- How to write file using Files.newBufferedWriter?
- How do I move a file in JDK 7?
- How to get the file name when using WatchService?
- How to read file using Files.newBufferedReader?
How do I change the buffer mode between write and read?
A buffer can be read or written. To change the mode between the write mode and read mode we use the flip() method call on the buffer.
The are few things that you should know when you change between the write mode to the read mode. A buffer have the capacity, position and limit properties. The capacity will always be the same on write or read mode. But the position and limit will store different information in each mode.
In write mode the limit will be equals to the capacity, but in read mode the limit will be equals to the last position where the last data were written. The position on the write mode point where the data will be written in the buffer. When calling the flip() method the position will be set to 0 and the limit will be set to the last value of the position.
package org.kodejava.example.nio;
import java.nio.CharBuffer;
public class BufferFlip {
public static void main(String[] args) {
CharBuffer buffer = CharBuffer.allocate(1024);
System.out.println("capacity = " + buffer.capacity());
System.out.println("position = " + buffer.position());
System.out.println("limit = " + buffer.limit());
buffer.put("Java NIO Programming");
System.out.println("capacity = " + buffer.capacity());
System.out.println("position = " + buffer.position());
System.out.println("limit = " + buffer.limit());
buffer.flip();
System.out.println("capacity = " + buffer.capacity());
System.out.println("position = " + buffer.position());
System.out.println("limit = " + buffer.limit());
}
}
The program will print the following result:
capacity = 1024 position = 0 limit = 1024 capacity = 1024 position = 20 limit = 1024 capacity = 1024 position = 0 limit = 20