Lab06-Handout Binary Files PDF

Title Lab06-Handout Binary Files
Course Intermediate Object-Oriented Programming
Institution La Trobe University
Pages 9
File Size 171.6 KB
File Type PDF
Total Downloads 4
Total Views 650

Summary

Intermediate Object-Oriented Programming Laboratory 06 (Week 07) Handout Objectives: This lab aims to cover Java I/O with binary files. More specifically, there are two objectives: 1. To practise using the File class 2. To learn how to work with binary files, including the use of the Serializable in...


Description

Intermediate Object-Oriented Programming Laboratory 06 (Week 07) Handout Objectives: This lab aims to cover Java I/O with binary files. More specifically, there are two objectives: 1. To practise using the File class 2. To learn how to work with binary files, including the use of the Serializable interface Question 1 a)

First copy the binary files numbers1.bin (a binary file of integer numbers) and rules1.bin (a binary file of Strings) from the library area using: cp cp

/home/1st/csilib/cse1ioo/lab06/numbers1.bin . /home/1st/csilib/cse1ioo/lab06/rules1.bin .

(Also available on LMS) Then write a program called ReadRulesV1.java that reads 5 numbers and 5 rules (strings) from each file and display the numbers and the rules, in pair, on the screen. The number is right-aligned in 4 spaces, followed by a colon, a space then the corresponding rule. Use one line for each number and rule. Write this program without try statements. Propagate any exceptions. b) Copy the binary files numbers2.bin and rules2.bin from the library area and alter your program in part a) to test your code using these input files. Observe the result and explain what happens. In particular, identify the statement that throws the exception. c)

Copy the binary files numbers3.bin and rules3.bin from the library area. Alter your program in part b) to test your code using these input files. Observe the result and explain what happens. In particular, identify the statement that throws the exception.

d) Consider this requirement: if either file contains less than 5 entries, the program should only output that many number of entries. Make a copy of ReadRulesV1, rename it ReadRulesV2, and modify your program to satisfy that requirement. Test your new program with the 3 pairs of binary files provided. e)

Does your program ReadRulesV2 handle exceptions other than EOFException? If not, make a copy, rename it ReadRulesV3, and modify it so that it can handle other exceptions (e.g. FileNotFoundException). Test your program with a test case which generates a FileNotFoundException.

1

Question 2 a)

Copy the files Person.java, Date.java, Contacts.java and ContactMenu.java from the library area into your current directory using the single unix command: cp

/home/1st/csilib/cse1ioo/lab06/*.java

.

These four Java files (reproduced at the end of this handout) form an application program that allows a user to add a person to their collection of contacts, display a birthday list and display a contacts list. Familiarise yourself with the program code, and run the program to see how it works. b) Currently, the program does not store any information between runs. It is your task to add this functionality to the program. When the program terminates all the data stored in the contacts attribute of the ContactMenu class must be saved to a binary file. Complete the method saveDatabase() in ContactMenu, so that the contacts attribute is saved to the binary file contactdb.bin. Catch any exception that may be generated during this process. c)

Next you are to modify the program to read data from contactdb.bin. When the ContactMenu program is executed, the contents of the file contactdb.bin should be read in automatically and stored back in the contacts attribute of class ContactMenu. Complete the method loadDatabase() in ContactMenu, so that contactdb.bin is opened and a Contacts object read from it and stored in the contacts attribute. Catch any exception that may be generated during this process.

d) Compile and run the changed program and verify that the program now stores data between runs.

2

Question 3 We also want the program to be able to save its data in text format so that we can view the contact data from outside the program. The requirements are as follows:   

The program must ask the user for the directory name. If the directory name specified cannot be used (that is a file with that name exists), then an error message is displayed and no contact details are written out. If the directory does not exist, it must be created before the contact details can be written to it.



If the directory is available, a text file is created for each contact stored in the contacts attribute. If the program detects the presence of a text file with the required name, then a message indicating that you are overwriting the existing file should be displayed.



Each contact is written to a file with the name of the contact and a “.contact” extension. For example, Fred Smith’s contact details would be written to the file Fred_Smith.contact in the directory the user specified.



The contact cards are output with the following format: Name: Smith, Fred Birthday: 1/4/1800 Email: [email protected] Phone: 9479 1111



An example run of this menu option follows: Enter directory to output contact cards in: friends Overwriting existing contact card: friends/Fred_Smith.contact Creating new contact card: friends/Jane_Doe.contact

First, add the following method to Contacts.java, which takes a File object representing the output directory and writes all the contact cards to this directory. Then, complete the makeContactCards() method of ContactMenu.java.

3

Listing of Classes Provided public class Date { private int day; private int month; private int year; public Date(int day, int month, int year) { this.day = day; this.month = month; this.year = year; } public int getDay() { return day; } public int getMonth() { return month; } public int getYear() { return year; } public boolean comesEarlierInYear(Date other) { if (month < other.getMonth()) { return true; } else if (month > other.getMonth()) { return false; } else { return day < other.getDay(); } } public boolean comesBefore(Date other) { if (year < other.getYear()) { return true; } else if (year > other.getYear()) { return false; } else if (month < other.getMonth()) { return true; } else if (month > other.getMonth()) { return false; } else { return day < other.getDay(); } } public String toString() { return day + "/" + month + "/" + year; } } // end of class Date

4

import java.io.*; public class Person { private String familyName; private String givenName; private Date birthDate; private String emailAddress; private String phoneNumber; public Person(String familyName, String givenName, int birthDay, int birthMonth, int birthYear, String email, String phone) { this.familyName = familyName; this.givenName = givenName; this.birthDate = new Date(birthDay, birthMonth, birthYear); this.emailAddress = email; this.phoneNumber = phone; } public String getFamilyName() { return familyName; } public String getGivenName() { return givenName; } public Date getBirthDate() { return birthDate; } public String getEmailAddress() { return emailAddress; } public String getPhoneNumber() { return phoneNumber; } public void setEmailAddress(String newEmail) { emailAddress = newEmail; } public void setPhonenNumber(String newPhoneNumber) { phoneNumber = newPhoneNumber; } public void setFamilyName(String newFamilyName) { familyName = newFamilyName; } public void setGivenName(String newGivenName) { givenName = newGivenName; } public boolean isOlderThan(Person otherPerson) { return birthDate.comesBefore(otherPerson.getBirthDate()); } public boolean birthdayComesBefore(Person otherPerson) { return birthDate.comesEarlierInYear(otherPerson.getBirthDate()); }

5

public boolean birthdayComesAfter(Person otherPerson) { return !birthdayComesBefore(otherPerson); } public int compareTo(Person otherPerson) { if (familyName.compareTo(otherPerson.getFamilyName()) != 0) { return familyName.compareTo(otherPerson.familyName); } else { return givenName.compareTo(otherPerson.givenName); } } public void outputContact(PrintWriter output) { output.println("Name: " + familyName + ", " + givenName); output.println("Birthday: " + birthDate); output.println("Email: " + emailAddress); output.println("Phone: " + phoneNumber); } public String getBirthdayListingLine() { return birthDate.getDay() + "/" + birthDate.getMonth() + "\t" + givenName + " " + familyName; } public String getContactListingLine() { return givenName + " " + familyName + " Email: " + emailAddress + " " + "Phone: " + phoneNumber; } } // end of class Person -----------------------------------------------------------------------------------------------import java.io.*; public class Contacts { private Person[] contactList; private int numberOfContacts; public Contacts() { contactList = new Person[16]; numberOfContacts = 0; } public void add(Person p) { if (numberOfContacts >= contactList.length) { doubleArray(); } contactList[numberOfContacts] = p; ++numberOfContacts; } private void doubleArray() { Person[] newArray = new Person[contactList.length * 2]; for (int i = 0; i < contactList.length; ++i) { newArray[i] = contactList[i]; } contactList = newArray; }

6

public void birthdayList(PrintWriter outstream) { sortByBirthday(); for (int i = 0; i < numberOfContacts; ++i) { outstream.println(contactList[i].getBirthdayListingLine()); } } private void sortByBirthday() { for (int i = numberOfContacts - 1; i > 0; --i) { int indexOfLatest = indexOfLatestDate(0, i); swap(i, indexOfLatest); } } private int indexOfLatestDate(int start, int end) { int indexOfLatest = start; for (int i = start + 1; i 0; --i) { int indexOfBiggest = indexOfBiggest(0, i); swap(i, indexOfBiggest); } } private int indexOfBiggest(int start, int end) { int indexOfBiggest = start; for (int i = start + 1; i 0) { indexOfBiggest = i; } } return indexOfBiggest; } } // end of class Contacts

7

import java.util.*; import java.io.*; public class ContactMenu { private Contacts contacts = new Contacts(); private Scanner keyboard = new Scanner(System.in); public void menu() { char input; do { System.out.println("Please select an option"); System.out.println("A - Add a person"); System.out.println("M - Make contact cards"); System.out.println("B - Birthday list"); System.out.println("C - Contact detail summary"); System.out.println("Q - Quit"); input = keyboard.next().trim().toUpperCase().charAt(0); keyboard.nextLine(); switch(input) { case 'A': addPerson(); break; case 'M': makeContactCards(); break; case 'B': generateBirthdayList(); break; case 'C': outputContactList(); break; case 'Q': System.out.println("Exiting system..."); break; default: System.out.println("That was not a valid choice!"); } } while (input != 'Q'); } public void addPerson() { System.out.println("Enter family name: "); String familyName = keyboard.nextLine(); System.out.println("Enter given name: "); String givenName = keyboard.nextLine(); System.out.println("Enter birthday [DD/MM/YYYY]: "); String birthday = keyboard.nextLine(); String[] birthdates = birthday.split("/"); System.out.println("Enter email address: "); String email = keyboard.nextLine(); System.out.println("Enter phone number: "); String phoneNumber = keyboard.nextLine(); Person newPerson = new Person(familyName, givenName, Integer.parseInt(birthdates[0]), Integer.parseInt(birthdates[1]), Integer.parseInt(birthdates[2]), email, phoneNumber); contacts.add(newPerson); } public void makeContactCards() { System.out.println("This menu option has not been implemented yet"); }

8

public void generateBirthdayList() { contacts.birthdayList(new PrintWriter(System.out, true)); } public void outputContactList() { contacts.contactList(new PrintWriter(System.out, true)); } public void loadDatabase() {} public void saveDatabase() {} public static void main(String[] args) { ContactMenu addressBook = new ContactMenu(); addressBook.loadDatabase(); addressBook.menu(); addressBook.saveDatabase(); } } // end of class ContactMenu



9...


Similar Free PDFs