日期:2014-05-16  浏览次数:20437 次

JAVA 性能提升之 MappedByteBuffer(内存映射)

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

public class LargeMappedFiles {

	static int length = 0x8FFFFFF;//128M
	public static void main(String[] args) {
		try {
			MappedByteBuffer out = new RandomAccessFile("test.txt", "rw").getChannel().map(FileChannel.MapMode.READ_WRITE, 0, length);
			for(int i = 0 ; i < length ; i ++){
				out.put((byte)i);
			}
			System.out.println("Finished writing");
			for(int i = length/2 ; i < length/2 + 6 ; i ++){
				System.out.println((char)out.get(i));
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
?