ListPeople.java 1.58 KB
Newer Older
temporal's avatar
temporal committed
1 2 3 4 5 6 7 8 9 10 11
// See README.txt for information and build instructions.

import com.example.tutorial.AddressBookProtos.AddressBook;
import com.example.tutorial.AddressBookProtos.Person;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;

class ListPeople {
  // Iterates though all people in the AddressBook and prints info about them.
  static void Print(AddressBook addressBook) {
12
    for (Person person: addressBook.getPeopleList()) {
temporal's avatar
temporal committed
13 14
      System.out.println("Person ID: " + person.getId());
      System.out.println("  Name: " + person.getName());
Jan Tattermusch's avatar
Jan Tattermusch committed
15
      if (!person.getEmail().isEmpty()) {
temporal's avatar
temporal committed
16 17 18
        System.out.println("  E-mail address: " + person.getEmail());
      }

Jan Tattermusch's avatar
Jan Tattermusch committed
19
      for (Person.PhoneNumber phoneNumber : person.getPhonesList()) {
temporal's avatar
temporal committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
        switch (phoneNumber.getType()) {
          case MOBILE:
            System.out.print("  Mobile phone #: ");
            break;
          case HOME:
            System.out.print("  Home phone #: ");
            break;
          case WORK:
            System.out.print("  Work phone #: ");
            break;
        }
        System.out.println(phoneNumber.getNumber());
      }
    }
  }

  // Main function:  Reads the entire address book from a file and prints all
  //   the information inside.
  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println("Usage:  ListPeople ADDRESS_BOOK_FILE");
      System.exit(-1);
    }

    // Read the existing address book.
    AddressBook addressBook =
      AddressBook.parseFrom(new FileInputStream(args[0]));

    Print(addressBook);
  }
}