<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