---
title: "MappedByteBuffer nio内存映射文件"
author: "沐雨川"
date: "2014-09-19T17:23:21Z"
tags: []
categories: ["编程语言"]
slug: "mappedbytebuffer-nio"
draft: false
lastmod: "2014-09-19T17:23:21Z"
id: 2118342
url: "https://jayke516.iteye.com/blog/2118342"
---

内存映射文件允许我们创建和修改哪些因为太大而不能放入内存的文件。有了内存映射文件，我们就可以假定整个文件都放在内存中，而且完全可以把它当做非常大的数组来访问。这种方法极大地简化了用于修改文件的代码。

import java.io.IOException;  
import java.io.RandomAccessFile;  
import java.nio.MappedByteBuffer;  
import java.nio.channels.FileChannel;

public class LargeMappedFiles {  
 static int length = 0x8ffffff;  
 public static void main(String\[] args) throws IOException{  
  MappedByteBuffer out = new RandomAccessFile("tt.dat",  
    "rw").getChannel().map(FileChannel.MapMode.READ\_WRITE, 0, length);  
  for(int i = 0; i &lt; length; i++)  
   out.put((byte)'x');  
  System.out.println("Finished Writing");  
  for(int i = length/2; i &lt; length/2 + 6; i++)  
   System.out.print((char)out.get(i));  
 }  
}

    为了既能读又能写，我们由RandomAccessFile开始，获取该文件上的通道，然后调用map()产生MappedByteBuffer，这是一种特殊类型的直接缓冲器。注意我们必须制定映射文件的初始位置和映射区域的长度，这意味着我们可以映射某个大文件的较小的部分。

    MappedByteBuffer由ByteBuffer继承而来，因此它具有ByteBuffer的所有方法。