Share on Google+Share on Google+

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.


import java.nio.*;
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 =;
System.out.print("Without rewind the content of buffer :\n");
    while (buf.hasRemaining()) {
System.out.print("\nAfter using rewind content of buffer : \n");
    while (buf.hasRemaining()) {

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


Posted on: July 24, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.