Java read file in memory

Ads
 

Java read file in memory

In this section, you will learn how to read a 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.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.

Ads

Ads