FileChannel

Read from Channel with ByteBuffer

This is an example of how to read data from a NIO Channel using a ByteBuffer in Java. In particular we are going to read data from a specific file in the file system and print them on screen. In short what we do is the following :

  • To read data from channel you should create a ReadableByteChannel. To do so you can create a FileInputStream object to encapsulate the target file. Then use the getChannel() API method of the FileInputStream object to get the file channel to read data from
  • We can allocate a new direct (memory-mapped) byte buffer by using the ByteBuffer class allocateDirect(int) API method
  • To read a sequence of bytes from the channel and write them to the given buffer all you have to do is use the read(ByteBuffer) API method of the ReadableByteChannel class providing the buffer as the input attribute. Do not forget to rewind() the buffer prior writing the contents from the channel since the writing will be done from the buffer’s current position on-wards. The same applies when you want to read data from the buffer

as described in the code snippet below.


 
Do not forget to close the channel after you are done processing the file so as to release operating system resources.

package com.javacodegeeks.snippets.core;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;

public class ReadFromChannelWithByteBuffer {
	
	public static void main(String[] args) {
		
		try {
			
		    // source file channel
			// return the unique FileChannel object associated with this file input stream.
		    ReadableByteChannel channel = new FileInputStream("in.xml").getChannel();

		    // Allocate a new direct (memory-mapped) byte buffer with a 10 byte capacity
		    ByteBuffer	buf = ByteBuffer.allocateDirect(10);

		    int bytesRead = 0;
		    
		    while (bytesRead >= 0) {
		    	
		
  // Rewind this buffer. The position is set to zero and the mark is discarded.
		
  buf.rewind();

		
  // Read a sequence of bytes from this channel into the given buffer.
		
  bytesRead = channel.read(buf);

		
  // in order to read the new bytes, the buffer has to be rewinded
		
  buf.rewind();

		
  // read all the bytes in the buffer
		
  for (int i=0; i<bytesRead; i++) {
		
  	// Read the byte at this buffer's current position, and then increments the position.
		

byte b = buf.get();
		

System.out.println("Byte read: " + b);
		
  }
		
  
		    }
		    
		}
		catch (IOException e) {
			System.out.println("I/O Error: " + e.getMessage());
		}
		
	}

}

This was an example of how to read data from a NIO Channel using a ByteBuffer in Java.

Want to know how to develop your skillset to become a Java Rockstar?

Join our newsletter to start rocking!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button