Java file in memory


 

Java file in memory

This section illustrates you how to map an entire file into memory for reading.

This section illustrates you how to map an entire file into memory for reading.

Java file in memory

This section illustrates you how to map an entire file into memory for reading.

Description of code:

We used the FileChannel class along with the ByteBuffer class to perform memory-mapped IO for data of type byte. These byte is then retrieved by using get() method of ByteBuffer class.

FileChannel: This is an abstract class which is used for reading, writing, mapping, and manipulating a file.

ByteBuffer: This is an abstract class which provides methods for reading and writing values of all primitive types except Boolean.

map() method: This method of FileChannel class maps the region of the channel's file directly into memory.

size() method: This method of FileChannel class returns the current size of this channel's file.

Here is the code:

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

public class FileInMemory {
	public static void main(String[] args) throws Exception {
		File file = new File("c:/data.txt");
		long length = file.length();
		FileChannel channel = new RandomAccessFile(file, "r").getChannel();
		ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0,
				(int) channel.size());
		int i = 0;
		while (i < length)
			System.out.print((char) buffer.get(i++));
	}
}

Ads