Share on Google+Share on Google+

How to clean a buffer using clear method in java.

In this tutorial you will see how to clean a buffer using clear method in java.

How to clean a buffer using clear method in java.

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

               In this example, the clear() method clean a buffer for further use, and after clear
 method the position will be zero and limit will be capacity of buffer. The method allocate
( int capacity) creates a new byte buffer. The FileChannel class creates a channel for reading,
and writing file. The FileChannel is similar to the stream but they are few different. 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.

About ByteBuffer API:

The java.nio.ByteBuffer class extends java.nio.Buffer class. It provides the following methods:

Return type Method Description
static ByteBuffer allocate( int capacity)  The allocate() method create a byte buffer of specified capacity. 


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

public class ByteBufferClear {
public static void main(String[] argsthrows IOException {
FileInputStream aFile = new FileInputStream("bharat.txt");
 FileInputStream bFile = new FileInputStream("test.txt");
    FileChannel inChannel = aFile.getChannel();
    FileChannel inChannelb = bFile.getChannel();
    ByteBuffer buf = ByteBuffer.allocate(55);
    int bytesRead =;
System.out.print("\nBefore clear method data in buffer\n");
    while (buf.hasRemaining()) {
    int bytesReadb =;
System.out.print("\nAfter clear method data in buffer\n");
    while (buf.hasRemaining()) {

Following is the output if you run the application:

C:\>java ByteBufferClear
Before clear method data in buffer
import java.nio.ByteBuffer;
import java.nio.channels.F
After clear method data in buffer

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.