首先用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
<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>
<dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>2.4.1</version> </dependency>
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()); } }
mvn clean compile mvn exec:java
Welcome to the Java sample for protocol buffer! freebird [email protected]