<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>
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; }
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