Use of rewind method in java.


 

Use of rewind method in java.

In this tutorial you will see use of rewind method in java.

In this tutorial you will see use of rewind method in java.

Use of rewind method in java.

      In this tutorial, we will explain the use of rewind() method of Buffer class. The ByteBuffer class 
is a container for handling data.The ByteBuffer class is available in java.nio package. 

      In this example, The rewind method reset the position of buffer at zero. So you can again 
read the buffer. The method allocate( int capacity) of ByteBuffer class creates a new byte 
buffer. The FileChannel class creates a channel for reading, and writing file. The channel can 
read write both, but stream can either read-only or write-only. The getChannel method of 
FileInputStream class returns the channel associated with this file input stream. The read()
 method of FileChannel class fills byte buffer created by using allocate() method.

code

import java.io.*;
import java.nio.*;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class ByteBufferRewind {
  public static void main(String[] argsthrows IOException {
    FileInputStream aFile = new FileInputStream("bharat.txt");
    FileChannel inChannel = aFile.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(55);
    int bytesRead = inChannel.read(buf);
    buf.flip();
System.out.print("Without rewind the content of buffer :\n");
    while (buf.hasRemaining()) {
      System.out.print((charbuf.get());
    }
    buf.rewind();
System.out.print("\nAfter using rewind content of buffer : \n");
    while (buf.hasRemaining()) {
      System.out.print((charbuf.get());
    }
    aFile.close();
  }
}

Following is the output if you run the application:

C:\>java ByteBufferRewind
Without rewind the content of buffer :
import java.nio.ByteBuffer;
import java.nio.channels.F
After using rewind content of buffer :
import java.nio.ByteBuffer;
import java.nio.channels.F

Download this code

Ads