`
单眼皮大娘
  • 浏览: 110810 次
  • 性别: Icon_minigender_2
  • 来自: 上海
社区版块
存档分类
最新评论

protobuf简单写入和读入例子

阅读更多
package protobuf.proto;
option java_outer_classname = "HtmlThemeProtos";
message HtmlTheme {
  required int32 id = 1;
  optional string title = 2;
  optional string data = 3;
}



package protobuf.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import database.DatabaseUtil;
import protobuf.proto.HtmlThemeProtos.HtmlTheme;
import protobuf.proto.HtmlThemeProtos.HtmlTheme.Builder;

public class WriteToFile {
	
	public static void main(String[] args) throws ClassNotFoundException, SQLException, IOException {
		String file = "G:/corpus/protobuf/TIME.txt";
		String querySQL = "SELECT * FROM TIME";
		Connection conn = DatabaseUtil.getConnection();
		Statement statement = conn.createStatement();
		ResultSet resultSet = statement.executeQuery(querySQL);
		
		FileOutputStream outputStream = new FileOutputStream(new File(file));
		
		System.out.println("BEGIN");
		int count = 0;
		while (resultSet.next()) {
			int id = resultSet.getInt(1);
			String title = resultSet.getString(2);
			String data = resultSet.getString(3);
			if (title == null || data == null) {
				count++;
				continue;
			}
			Builder htmlThemeBuilder = HtmlTheme.newBuilder();
			htmlThemeBuilder.setId(id);
			htmlThemeBuilder.setTitle(title);
			htmlThemeBuilder.setData(data);
			HtmlTheme build = htmlThemeBuilder.build();
			build.writeDelimitedTo(outputStream);
			
		}
		
		resultSet.close();
		statement.close();
		conn.close();
		outputStream.flush();
		outputStream.close();
		
		System.out.println("DONE");
		System.out.println("====================================");
		System.out.println(count);
		System.out.println("====================================");
	}
}



package protobuf.impl;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import protobuf.proto.HtmlThemeProtos.HtmlTheme;

public class ReadFromFile {
	public static void main(String[] args) throws IOException {
		String file = "G:/corpus/protobuf/TIME.txt";
		FileInputStream inputStream = new FileInputStream(new File(file));
		HtmlTheme htmlTheme;
		int count = 0;
		while ((htmlTheme = HtmlTheme.parseDelimitedFrom(inputStream)) != null) {
			System.out.println(htmlTheme.getId() + "\t\t" + htmlTheme.getTitle());
			count++;
		}
		
		System.out.println("===============================");
		System.out.println(count);
		System.out.println("===============================");
		
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics