0

I'm following Googles tutorial on Protocol Buffers using Java: https://developers.google.com/protocol-buffers/docs/javatutorial

and I'm struggling as to how the tutorial writes to a file (i.e. taking user input)? What type of file do you write to? a .proto or .txt (or however you want to save your data).

addressbook.proto :

package tutorial;

option java_package = "com.example.tutorial";
option java_outer_classname = "AddressBookProtos";

message Person {
  required string name = 1;
  required int32 id = 2;
  optional string email = 3;

  enum PhoneType {
    MOBILE = 0;
    HOME = 1;
    WORK = 2;
  }

  message PhoneNumber {
    required string number = 1;
    optional PhoneType type = 2 [default = HOME];
  }

  repeated PhoneNumber phone = 4;
}

message AddressBook {
  repeated Person person = 1;
} 

I'm not going to paste the file here on Stack I've compiled to java with protoc. I done that using

protoc -I=$SRC_DIR --java_out=$DST_DIR $SRC_DIR/addressbook.proto 

in terminal.

 Generated File Link - http://pastebin.com/1w7ibDru
 I've also downloaded the Protobuf 2.5.0 jar and added it as a library to my project

AddPerson.java :

import com.example.tutorial.AddressBookProtos.AddressBook;
import com.example.tutorial.AddressBookProtos.Person;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintStream;

class AddPerson {
  // This function fills in a Person message based on user input.
  static Person PromptForAddress(BufferedReader stdin,
                                 PrintStream stdout) throws IOException {
    Person.Builder person = Person.newBuilder();

    stdout.print("Enter person ID: ");
    person.setId(Integer.valueOf(stdin.readLine()));

    stdout.print("Enter name: ");
    person.setName(stdin.readLine());

    stdout.print("Enter email address (blank for none): ");
    String email = stdin.readLine();
    if (email.length() > 0) {
      person.setEmail(email);
    }

    while (true) {
      stdout.print("Enter a phone number (or leave blank to finish): ");
      String number = stdin.readLine();
      if (number.length() == 0) {
        break;
      }

      Person.PhoneNumber.Builder phoneNumber =
        Person.PhoneNumber.newBuilder().setNumber(number);

      stdout.print("Is this a mobile, home, or work phone? ");
      String type = stdin.readLine();
      if (type.equals("mobile")) {
        phoneNumber.setType(Person.PhoneType.MOBILE);
      } else if (type.equals("home")) {
        phoneNumber.setType(Person.PhoneType.HOME);
      } else if (type.equals("work")) {
        phoneNumber.setType(Person.PhoneType.WORK);
      } else {
        stdout.println("Unknown phone type.  Using default.");
      }

      person.addPhone(phoneNumber);
    }

    return person.build();
  }

  // Main function:  Reads the entire address book from a file,
  //   adds one person based on user input, then writes it back out to the same
  //   file.
  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println("Usage:  AddPerson ADDRESS_BOOK_FILE");
      System.exit(-1);
    }

    AddressBook.Builder addressBook = AddressBook.newBuilder();

    // Read the existing address book.
    try {
      addressBook.mergeFrom(new FileInputStream(args[0]));
    } catch (FileNotFoundException e) {
      System.out.println(args[0] + ": File not found.  Creating a new file.");
    }

    // Add an address.
    addressBook.addPerson(
      PromptForAddress(new BufferedReader(new InputStreamReader(System.in)),
                       System.out));

    // Write the new address book back to disk.
    FileOutputStream output = new FileOutputStream(args[0]);
    addressBook.build().writeTo(output);
    output.close();
  }
}

I obviously get the error:

Usage:  AddPerson ADDRESS_BOOK_FILE

I presume the AddPerson class takes in a File (a .txt perhaps?) in main and there is no file, hence why?

// Main function:  Reads the entire address book from a file,
  //   adds one person based on user input, then writes it back out to the same
  //   file.

The comment says file, but I don't know what type of file?

Can someone show me what I'm suppose to do to actually write to a file. I'm not too sure what type of file to write to as well.

There is not that many Protobuf tutorials out there :/

Forgive me if this questions is trivial, I have never worked with proto buffers.

Thank you.

Adz
  • 2,809
  • 10
  • 43
  • 61
  • 1
    It's a protocol buffers file, basically - one written with `writeTo(output)` as per the end of the code. – Jon Skeet Aug 14 '14 at 20:14
  • Ok, but my code doesn't execute. I can't enter anything. Error: Usage: AddPerson ADDRESS_BOOK_FILE – Adz Aug 14 '14 at 20:19
  • 1
    Well that suggests that you're not passing in a command line argument... you want `java AddPerson addresses.dat` (or whatever you want the filename to be) – Jon Skeet Aug 14 '14 at 20:21
  • Hmm, ok, if I add the " java AddPerson addresses.dat " to Run Configurations arguments I get a Could not find or load main class AddPerson. Am I passing the argument wrong? Sorry! – Adz Aug 14 '14 at 21:17
  • 2
    Yes, you're passing the argument wrong. I didn't realize you were using Eclipse. I'm not at a computer right now, but you just need to run the AddPerson class with one argument - the filename. – Jon Skeet Aug 14 '14 at 21:19
  • 1
    Yes, that worked Jon, thank you very much once again! – Adz Aug 14 '14 at 21:20
  • @JonSkeet I'm having the same issue. What is the command you finally used? I'm not using eclipse I've did this: `java -cp /home/matthias/Workbench/SUTD/proto_buff/protobuf-2.6.1/java/target/protobuf-java-2.6.1.jar AddPerson addresses.dat` and I get the error `Could not find or load main class AddPerson`, why is that? – smatthewenglish Apr 09 '15 at 05:51
  • @S.Matthew_English: With that command, your classpath *only* includes the protobuf jar file. You need to include the addressbook sample output directory on the classpath as well... – Jon Skeet Apr 09 '15 at 06:20
  • @JonSkeet I figured it out. It works with this `java -cp /home/matthias/Workbench/SUTD/proto_buff/protobuf-2.6.1/java/target/protobuf-java-2.6.1.jar:. AddPerson addresses.dat ` what was missing was that `:.`, what is that thing anyway? It seems to be along the lines of, "now forget about the classpath and consider again the current directory", is that is? – smatthewenglish Apr 09 '15 at 06:32
  • @S.Matthew_English: This is now *way* off the topic of the question. It's just plain Java classpath behaviour - `:` is the path separator on Unix, and `.` is the current directory. – Jon Skeet Apr 09 '15 at 06:35
  • @JonSkeet seems like you're an expert. would you be willing to consider [this](http://stackoverflow.com/questions/29531899/how-to-write-a-valid-decoding-file-based-on-a-given-proto-reading-from-a-pb) question, which is, in fact, more topical – smatthewenglish Apr 09 '15 at 07:03

0 Answers0