MappedByteBuffer 高效读写文件

    private static final int start = 0;
    public static void main(String[] args) throws IOException {

        RandomAccessFile raf = new RandomAccessFile("D:/mapper.txt", "rw");
        FileChannel fileChannel = raf.getChannel();

        String a = "我要写入文件";
        MappedByteBuffer mbb = fileChannel.map(FileChannel.MapMode.READ_WRITE, start, a.getBytes().length+1);
        mbb.put(a.getBytes());

        mbb.flip();

        byte[] bb = new byte[mbb.capacity()];
        while (mbb.hasRemaining()){
            byte b = mbb.get();
            bb[mbb.position()]=b;
        }
        System.out.println(new String(bb));
        raf.close();

    }

你可能感兴趣的:(tips)