网上搜索了代码:
使用byte数组缓冲的,不能用。
如何使用内存映射,没有可用代码。
只好自己研究,先从简单的开始。目前还将就着能用。
package quantum6; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; public final class BufferedRandomAccessFile extends RandomAccessFile { private static final int BUFFER_SIZE = 1024*1024; private String filePath; private int outSize = BUFFER_SIZE; private MappedByteBuffer mbbi; private MappedByteBuffer mbbo; public BufferedRandomAccessFile(File file, String mode) throws FileNotFoundException { this(file, mode, file.length()); } public BufferedRandomAccessFile(File file, String mode, long size) throws FileNotFoundException { super(file, mode); filePath = file.getAbsolutePath(); try { if (mode.contains("r")) { FileChannel fci = getChannel(); mbbi = fci.map(FileChannel.MapMode.READ_ONLY, 0, size); } if (mode.contains("w")) { FileChannel fco = getChannel(); mbbo = fco.map(FileChannel.MapMode.READ_WRITE, 0, size); } init(file.length()); } catch (IOException e) { throw new FileNotFoundException(); } } private void init(long size) throws IOException { /* bufferOffsetLeft = 0; bufferOffsetRight = size; bufferPointer = 0; bufferSize = (int)(size > BUFFER_SIZE ? size : BUFFER_SIZE); bufferData = new byte[bufferSize]; */ } public String getPath() { return filePath; } @Override public void seek(long pos) throws IOException { mbbi.position((int)pos); } @Override public int read() throws IOException { return mbbi.get(); } @Override public int read(byte[] b) throws IOException { return this.read(b, 0, b.length); } @Override public int read(byte[] b, int off, int len) throws IOException { int left = mbbi.remaining(); mbbi.get(b, off, len); return (mbbi.remaining() - left); } private void checkWriteBuffer() throws IOException { if (mbbo == null || !mbbo.hasRemaining()) { outSize += BUFFER_SIZE; FileChannel fco = getChannel(); mbbo = fco.map(FileChannel.MapMode.READ_WRITE, 0, outSize); } } @Override public void write(int b) throws IOException { checkWriteBuffer(); mbbo.put((byte)b); } @Override public void write(byte[] b) throws IOException { this.write(b, 0, b.length); } @Override public void write(byte[] b, int off, int len) throws IOException { checkWriteBuffer(); mbbo.put(b, off, len); } }