Protocol Buffer 三 简单例子之Java程序

首先用maven创建一个简单的Java application.

mvn archetype:generate -DgroupId=org.freebird.protocolbuffer -DartifactId=sample -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

创建的目录结构如下:

$ tree sample
sample
├── pom.xml
└── src
    ├── main
    │ └── java
    │     └── org
    │         └── freebird
    │             └── protocolbuffer
    │                 └── App.java
    └── test
        └── java
            └── org
                └── freebird
                    └── protocolbuffer
                        └── AppTest.java

由于之前Protocol buffer编译器生成的Java文件是外部的,因此需要一个plugin帮助加入到这个项目中来。

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>1.7</version>
        <executions>
          <execution>
            <id>add-source</id>
            <phase>generate-sources</phase>
            <goals>
              <goal>add-source</goal>
            </goals>
            <configuration>
              <sources>
                <source>../../../template/java</source>
              </sources>
            </configuration>
          </execution>
        </executions>
      </plugin>

并且之前的编译的protocol buffer的java库已经部署在自己的nexus私服上,现在可以使用dependency来引用它。

    <dependency>
      <groupId>com.google.protobuf</groupId>
      <artifactId>protobuf-java</artifactId>
      <version>2.4.1</version>
    </dependency>


现在来实现简单的Java程序。从参数指定的文件读取数据,反序列化成User对象。

package org.freebird.protocolbuffer;

import org.freebird.sample.UserProto.User;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Sample!
 *
 */
public class App {
    public static void main( String[] args ) throws IOException {
        System.out.println( "Welcome to the Java sample for protocol buffer!" );
	User user = User.parseFrom(new FileInputStream(args[0]));
	System.out.println(user.getName());
	System.out.println(user.getEmail());
    }
}

运行下面的命令(我假定你会使用exec plugin)

mvn clean compile
mvn exec:java

结果如下:

Welcome to the Java sample for protocol buffer!
freebird
shu_chen@esri.com

因此,protocol buffer的跨语言特性相当好用。





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值