Home Tutorial Java Corejava Nio Use of rewind method in java.

 
 

Use of rewind method in java.
Posted on: July 24, 2010 at 12:00 AM
Advertisement
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

Advertisement

Related Tags for Use of rewind method in java.:


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.

Posted on: July 24, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com