protobuf全称Google Protocol Buffers
1. 下载proto文件编译软件
下载路径:https://github.com/protocolbuffers/protobuf/releases
下载文件:protoc-25.1-win64.zip
将 bin 目录配置到环境变量path 中
2. pom引入protobuf-java
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.25.1</version>
</dependency>
3. 编译文件
在文件目录输入编译命令: protoc ./tran_data.proto --java_out=./
4. 测试方法
import com.google.protobuf.InvalidProtocolBufferException;
public class TestGpsProtobuf {
public static void main(String[] args) {
System.out.println("===== 构建一个GPS模型开始 =====");
PersonData.person_data.Builder builder = PersonData.person_data.newBuilder();
builder.setName("li.san");
builder.setAge(20);
builder.setSex("1");
builder.setScore(100.5);
builder.setSpeed(50.2F);
builder.setId(50L);
PersonData.person_data gpsData = builder.build();
System.out.println(gpsData.toString());
System.out.println("===== 构建模型结束 =====");
System.out.println("===== Byte 开始=====");
PersonData.person_data pd = null;
try {
pd = PersonData.person_data.parseFrom(gpsData.toByteArray());
} catch (InvalidProtocolBufferException e) {
e.printStackTrace();
}
System.out.println(String.valueOf(pd));
System.out.println("===== 反序列化生成对象结束 =====");
}
}