首页  

Java NIO 内存映射文件     所属分类 nio 浏览量 901
内存映射文件
FileChannel channel = FileChannel.open(path,options);
RandomAccessFile FileInputStream  FileOutputStream  getChannel()  

FileChannel
public abstract MappedByteBuffer map(MapMode mode,long position, long size)
                                         
                                         
position    起始位置
size        大小

mode 
FileChannel.MapMode.READ_ONLY    只读缓冲区
FileChannel.MapMode.READ_WRITE   可读写
FileChannel.MapMode.PRIVATE      缓冲区可修改,但不能将修改后的内容写到文件中


0 <= 标记 <= 位置 <= 界限 <= 容量


文件加锁机制
多个线程访问同一个文件可能损坏文件数据

FileLock lock = channel.lock();      
FileLock lock = channel.tryLock();    
lock.release();   

可锁定缓冲区的一部分

FileLock lock(long start, long size, boolean shared) 
FileLock tryLock(long start, long size, boolean shared)

文件加锁机制依赖于操作系统
不可重入锁  文件锁由JVM持有 ,重复加锁,OverlappingFileLockException


MappedByteBuffer 存在内存占用和文件关闭等不确定问题
被 MappedByteBuffer 打开的文件只有在GC时才会被关闭 

A mapped byte buffer and the file mapping that it represents remain valid until the buffer itself is garbage-collected. 



String home = System.getProperty("user.home"); System.out.println("home="+home); String str = "hello,java nio,FileChannelMapTest,"+LocalDateTime.now(); System.out.println(str); String file = home + "/FileChannelMapTest.txt" ; byte[] bytes = str.getBytes(); int length = bytes.length; System.out.println("length="+length); Path path = Paths.get(file); FileChannel fileChannel = FileChannel.open(path,StandardOpenOption.CREATE,StandardOpenOption.WRITE,StandardOpenOption.READ); MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, length); mappedByteBuffer.put(bytes); // mappedByteBuffer.force(); fileChannel.close(); fileChannel = FileChannel.open(path,StandardOpenOption.READ); mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, length); System.out.println("mappedByteBuffer.isLoaded()="+mappedByteBuffer.isLoaded()); // mappedByteBuffer.load(); System.out.println(mappedByteBuffer); bytes = new byte[length]; mappedByteBuffer.get(bytes); System.out.println(new String(bytes));
完整代码 https://gitee.com/dyyx/hellocode/blob/master/src/nio/FileChannelMapTest.java

上一篇     下一篇
java NIO FileChannel

Java NIO Scatter Gather

java NIO SocketChannel

java随机数生成器

ZGC指南

java GC 进化