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的移動方式來肯定讀取和寫入;此種方式內存能夠重複利用
  • 讀取的時候使用的是字節方式,此種方式簡單,可是每次都須要建立一個對象;對於數據量比較大的時候不建議使用
相關文章
相關標籤/搜索