大多數(shù)操作系統(tǒng)都可以利用虛擬內(nèi)存實(shí)現(xiàn)來將一個文件或者文件的一部分“映射”到內(nèi)存中搂赋。然后這個文件就可以當(dāng)作內(nèi)存數(shù)組一樣訪問赘阀,這比傳統(tǒng)的文件操作要快很多。
在java中脑奠,提供了FileChannel類來實(shí)現(xiàn)文件的內(nèi)存映射基公。使用FileChannel大致可以分為下面三個步驟:
- 調(diào)用FileChannel.open()方法,獲取一個FileChannel的引用
- 調(diào)用FileChannel的map方法宋欺,獲取到一個ByteBuffer.
- 操作ByteBuffer轰豆,獲取想要的數(shù)據(jù)
下面是一個簡單的演示demo:
Path path = Paths.get("d:\\hello.txt");
FileChannel fc = FileChannel.open(path, StandardOpenOption.READ);
long length = fc.size();
ByteBuffer buffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, length);
int size = buffer.limit();
byte[] data = new byte[size];
buffer.get(data);
String msg = new String(data, 0, data.length, Charset.forName("utf-8"));
System.out.println(msg);
有幾個參數(shù)還說有有必要說明一下:
open(Path path,OpenOpiton opitions):第一個參數(shù)表示文件的path路徑,第二個參數(shù)表示打開的可選項(xiàng)齿诞,一般使用StandardOpenOption中的枚舉值WRITE酸休、APPEND、TRUNCATE_EXISTING祷杈、CREATE斑司、READ等值。
map(FileChannel.MapMode mode, long position, long size):modes表示文件映射區(qū)域的映射模式但汞,有三個屬性FileChannel.MapMode.READ_ONLY表示所產(chǎn)生的緩沖區(qū)是只讀的宿刮;FileChannel.MapMode.READ_WRITE表示所產(chǎn)生的緩沖區(qū)是可寫的私蕾,任何修改都會在某個時刻寫回到文件中僵缺;FileChannel.MapMode.PRIVATE表示所產(chǎn)生的緩沖區(qū)是可寫的,任何對于緩沖區(qū)的修改都不會傳播到文件中踩叭。