FileChannel 使用ByteBuffer 和 Protostuff 从文件中读写 对象信息

protostuff

protostuff 包引入

<dependency>
		<groupId>io.protostuff</groupId>
		<artifactId>protostuff-runtime</artifactId>
		<version>1.6.0</version>
	</dependency>

	<dependency>
		<groupId>io.protostuff</groupId>
		<artifactId>protostuff-core</artifactId>
		<version>1.6.0</version>
	</dependency>

protostuff 简单实用 序列化和反序列化对象信息

private LinkedBuffer linkedBuffer = LinkedBuffer.allocate(4 * 1024);
    private Schema<ShowModel> schema = RuntimeSchema.getSchema(ShowModel.class);

    //对象转换成 byte
    private byte[] seriBean(){
        linkedBuffer.clear();
        ShowModel showModel = new ShowModel();
        showModel.setId(1);
        showModel.setName("demo");
        return ProtostuffIOUtil.toByteArray(showModel, schema, linkedBuffer);
    }

    //byte 转换成 对象
    private ShowModel deSeriBean(byte[] data){
        ShowModel showModel = schema.newMessage();
        ProtostuffIOUtil.mergeFrom(data, showModel, schema);
        return showModel;
    }

ByteBuffer

写入对象到文件中

String fileName = "e:\\aa.db";
    //定义读写文件
    FileChannel fileChannel = new RandomAccessFile(new File(fileName), "rw").getChannel();
    //定义4个字节的空间
    ByteBuffer byteBuffer = ByteBuffer.allocate(4);
    //定义一个大点的字节空间,重复利用
    ByteBuffer byteBufferContent = ByteBuffer.allocate(4 * 1024);
    for (int i = 0; i<12; i++){
        byte[] byteWrite = seriBean();
        int length = byteWrite.length;
        System.out.println("写入的长度为:" + length);
        byteBuffer.putInt(length);
        byteBuffer.flip();
        fileChannel.write(byteBuffer);

        byteBufferContent.put(byteWrite);
        //从0开始读取,读取到写入的长度
        byteBufferContent.flip();
        fileChannel.write(byteBufferContent);
        byteBuffer.clear();
        byteBufferContent.clear();
    }

从文件中读取字节成对象信息

ByteBuffer byteBuffer = ByteBuffer.allocate(4);
    fileChannel = new RandomAccessFile(new File(fileName), "rw").getChannel();
    while (fileChannel.read(byteBuffer) == 4){
        //把byteBuffer中的limit变成position(即4个字节),同时吧position定位成0 表示从0开始读取4个字节的数据,就是它的长度
        byteBuffer.flip();
        int length = byteBuffer.getInt();
        System.out.println("read ==>> " + length);
        byte[] b = new byte[length];
        fileChannel.read(ByteBuffer.wrap(b));
        System.out.println(deSeriBean(b).getName());
        byteBuffer.clear();
    }
    fileChannel.force(true);
    fileChannel.close();

注:java

  • 写入的时候使用的 纯ByteBuffer,采用 position 和 limit的移动方式来肯定读取和写入;此种方式内存能够重复利用
  • 读取的时候使用的是字节方式,此种方式简单,可是每次都须要建立一个对象;对于数据量比较大的时候不建议使用
相关文章
相关标签/搜索