ZOFTINO.COM android and web dev tutorials

Java Memory Mapped Files

A segment of virtual memory containing a part of a file which exists on the disk or other file resource is called memory mapped file. Operating system handles the memory mapping. Memory mapped files are useful to improve the performance of reading and writing of large files. It allows for lazing loading of file content into memory. Since memory mapping process is handled by the operating system, memory mapped files internal depends on the operating system.

In Java, you can create and access memory mapped files using FileChannel and MappedByteBuffer. FileChannel provides map() method which maps region of a file into memory and returns MappedByteBuffer object. You need to specify the position in the file from which the content needs to loaded into memory and size of the content that needs to be loaded as arguments to map() method.

FileChannel allows you to load part of the file into memory in three modes, read only mode, read and write mode and private mode. Memory mapped files created in private mode doesn’t save the changes in file. For creating read only memory mapped file, first you need to open the channel in read only mode. Similarly, to open memory mapped file for reading and writing, channel needs to be opened in read and write mode.

Steps to User Memory Mapped Files

First open the FileChannel in read, write or read and write mode.

	FileChannel fc = (FileChannel.open(filePath, StandardOpenOption.WRITE,
			StandardOpenOption.READ));

Get MappedByteBuffer object by calling map and passing map mode, position and size.

	MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE,
			position, pageSize);

To read data from memory mapped file, use appropriate MappedByteBuffer primitive get method or one of the methods which return buffers.

String content = Charset.forName("UTF-8").decode(mbb).toString()

To write data to memory mapped file, use put methods of MappedByteBuffer object.

mbb.put(bytebuffer);

Memory Mapped File Read Example

	public void readMemoryFile(String fileName, int page) {
		//page size - size to be loaded to memory
		int pageSize = 100;
		//from where to read within the file
		int position = page*pageSize;
		
		Path filePath = Paths.get(fileName);

		//Open file channel for read 
		try (FileChannel fc = (FileChannel.open(filePath,
				StandardOpenOption.READ))) {

			//create memory mapped file for the page to be viewed
			MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_ONLY,
					position, pageSize);
	        
			//process the content read from memory
			System.out.println(Charset.forName("UTF-8").decode(mbb));
			
		} catch (IOException ex) {
			System.out.println("exception in reading memory mapped file: "+ex);
			ex.printStackTrace();
		}
	}
memoryFileUtil.readMemoryFile(fileTwo, 5);

Memory Mapped File Write Example

	public void writeToMemoryFile(String fileName, String content, int page,
			int positionInPage) {
		//page size - size to be loaded to memory
		int pageSize = 100;
		//from where to read within the file
		int position = (page-1)*pageSize+positionInPage;
		
		Path filePath = Paths.get(fileName);
		
		byte contb[] = content.getBytes();
		ByteBuffer bb = ByteBuffer.wrap(contb);

		try (FileChannel fc = (FileChannel.open(filePath, 
								StandardOpenOption.WRITE,
								StandardOpenOption.READ))) {
			MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE,
					position, contb.length);			
			mbb.put(bb);
			mbb.force();
		} catch (IOException ex) {
			System.out.println("exception in writing to memory file: "+ex);
		}
	}
	String content = "best offer, upto 50% of jeans, 4% cashback on fashion";
	memoryFileUtil.writeToMemoryFile(fileTwo, content, 5, 10);

Other Tutorials Related to IO