Share on Google+Share on Google+

Java read file in memory

In this section, you will learn how to read a file in memory.

Java read file in memory

In this section, you will learn how to read a file in memory.

Description of code:

The class FileInputStream get a channel for the  file, and then call map( ) to produce a MappedByteBuffer, which is a particular kind of direct buffer and specify the starting point and the length of the region that you want to map in the file. The class MappedByteBuffer inherits all the methods of ByteBuffer class. The method get() reads the byte at the given index.

Here is the code:

import java.nio.*;
import java.nio.channels.*;

public class ReadFileInMemory {
	public static void main(String[] args) throws Exception {
		File f = new File("C:/hello.txt");
		long length = f.length();
		MappedByteBuffer buffer = new FileInputStream(f).getChannel().map(
				FileChannel.MapMode.READ_ONLY, 0, length);
		int i = 0;
		while (i < length) {
			System.out.print((char) buffer.get(i++));

The above code mapped the file in a memory and then read the file.


Posted on: March 1, 2011 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.