Home Tutorial Java Io Java read file in memory

 
 

Share on Google+Share on Google+
Java read file in memory
Posted on: March 1, 2011 at 12:00 AM
Advertisement
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.io.*;
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++));
		}
		System.out.println();
	}
}

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

Advertisement

Related Tags for Java read 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: March 1, 2011

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com