Home Tutorial Java Core Files Java file in memory

 
 

Share on Google+Share on Google+
Java file in memory
Posted on: April 26, 2006 at 12:00 AM
Advertisement
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++));
	}
}
Advertisement

Related Tags for Java file in memory:


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: April 26, 2006

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com