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("==============================="); } }