java mmap介绍
java mmap介绍
1.优点
public static void readTest(){ String bigFile = "D:/newfile.txt"; //Get file channel in read-only mode try(RandomAccessFile file = new RandomAccessFile(new File(bigFile),"r")){ FileChannel fileChannel = file.getChannel(); //Get direct byte buffer access using channel.map() operation MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_ONLY,0,fileChannel.size()); // the buffer now reads the file as if it were loaded in memory. System.out.println(buffer.isLoaded()); //prints false System.out.println(buffer.capacity()); //Get the size based on content size of file //You can read the file from this buffer the way you like. for (int i = 0; i < buffer.limit(); i++) { System.out.println((char)buffer.get()); } }catch(FileNotFoundException f){ f.printStackTrace(); }catch(IOException o){ o.printStackTrace(); } }
3.代码示例---写
public static void writeTest(){ String bigFile = "D:/newfile.txt"; String content = "java.com"; File file = new File(bigFile); file.delete(); try (RandomAccessFile randomAccessFile = new RandomAccessFile(file,"rw")){ FileChannel fileChannel = randomAccessFile.getChannel(); // Get direct byte buffer access using channel.map() operation MappedByteBuffer buffer = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, content.length()+10); //Write the content using put methods buffer.put("java.com".getBytes()); }catch(FileNotFoundException f){ f.printStackTrace(); }catch(IOException o){ o.printStackTrace(); } }
https://howtodoinjava.com/java/nio/memory-mapped-files-mappedbytebuffer/
https://xunnanxu.github.io/2016/09/10/It-s-all-about-buffers-zero-copy-mmap-and-Java-NIO/
浙公网安备 33010602011771号