Wednesday, June 19, 2013

Phonebook

This is a phonebook program that can be used to save a phonebook to a file, view all entries in the phonebook, add a new entry, delete an entry from the phonebook, find an entry by name, create pdf and html files of the phonebook.

The Hashtable data structure is used to store the list of phonebook entries. Each Hashtable entry contains the name and phone number. An operation (e.g add entry to phonebook) is performed on the Hashtable phonebook list. The updated phonebook list will be saved to the phonebook.bin file. When the program firstly loads, the file is read so that all entries in the phonebook are retrieved for later used in the program.

Phonebook in Java


phonebook html report

phonebook pdf report


PhoneBook source code:

import java.awt.Desktop;
import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfWriter;

//The PhoneBookEntry class is a template for every phonebook entry object
//that will be saved in a file called phonebook.bin
//Each entry has name and phone number
//The PhoneBookEntry must implement the Serializable interface since its object
//will be added to the Hashtable for saving in the file

class PhoneBookEntry implements Serializable{

private String Name;
private String Phone;

//constructor
PhoneBookEntry(String name,String phone){

this.Name=name;
this.Phone=phone;


}
//get name
public String getName(){
return Name;
}


//get phone number
public String getPhone(){
return Phone;
}

//print entry information
public void printInfo(){
System.out.println("Name:"+Name+", Phone:"+Phone);
}
}


public class PhoneBook{
static Hashtable<String,PhoneBookEntry> phonebook;
public static void main(String[] args){
phonebook=readList(); //read phonebook
int ch;
char con='y';
Scanner sc=new Scanner(System.in); //create scanner object to receive choice input

while(con=='y'){
showMenu(); //show menu
System.out.println("Enter your choice:");
ch=sc.nextInt();
switch(ch){
case 1:viewAll();break;
case 2:addToPhoneBook();break;
case 3:deleteFromPhonebook();break;
case 4:searchByName();break;
case 5:createPdf();break;
case 6:createHTML();break;
case 7:System.exit(0);break;
default: System.out.println("Invalid choice");
}

try{
//prompt for continuing the program
InputStreamReader isr=new InputStreamReader(System.in);
System.out.println("Press y to continue:");
con=(char)isr.read();
}catch(IOException ie){}


}


}
//The viewAll method displays all entries in the phonebook
public static void viewAll(){

if(phonebook!=null){

for(Enumeration<String> e=phonebook.keys(); e.hasMoreElements();){
PhoneBookEntry entry=phonebook.get(e.nextElement());
entry.printInfo();
}

}

}


//The addToPhoneBook method is able to add each entry to the phonebook
public static void addToPhoneBook(){
//If the phonebook null, allocate memory for it so it is ready to get the new item
if(phonebook==null) phonebook=new Hashtable<String,PhoneBookEntry>();
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter name:");
String name=br.readLine();
System.out.println("Enter phone:");
String phone=br.readLine();
PhoneBookEntry st=new PhoneBookEntry(name,phone);
phonebook.put(name,st); //add new entry to the phonebook
writeIt(phonebook); //save the update phonebook
}catch(IOException e){}
}

//The deleteFromPhonebook method is able to delete an entry when the name
//is correctly input
public static void deleteFromPhonebook(){
if(phonebook!=null){
int si=phonebook.size(); //number of entries in the phonebook before an entry is removed
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Name:");
String key=br.readLine();
phonebook.remove(key); //remove the contact
if(phonebook.size()<si){ //removing is successful
writeIt(phonebook);
System.out.println("The entry has been deleted.");
}
else
System.out.println("Wrong name");
}catch(IOException ie){}


}
}

//The searchByName method has code to find a phonebook entry by name in the list
public static void searchByName(){
if(phonebook!=null){
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Search by name:");
String key=br.readLine();
PhoneBookEntry cu=phonebook.get(key);
if(cu!=null)
cu.printInfo();

else
System.out.println("Not found");
}catch(IOException ie){}


}
}

//Write the Hashtable object representing the phonebook to the file
public static void writeIt(Hashtable<String,PhoneBookEntry> obj){
try{
FileOutputStream fos=new FileOutputStream("phonebook.bin");
ObjectOutputStream oos=new ObjectOutputStream(fos);
oos.writeObject(obj);
oos.flush();
oos.close();
}catch(IOException ie){}

}

//The readList method has code to read phonebook from the file

public static Hashtable<String,PhoneBookEntry> readList(){

Hashtable<String,PhoneBookEntry> phbook=null;
try{
FileInputStream fis=new FileInputStream("phonebook.bin");
ObjectInputStream ois=new ObjectInputStream(fis);
phbook=(Hashtable<String,PhoneBookEntry>)ois.readObject();
ois.close();

}catch(Exception ie){}
return phbook;

}
//create phonebook pdf file
public static void createPdf(){

if(phonebook!=null){
try{
//create document object
Document doc=new Document(PageSize.A4);
//create a pdf writer object to write text to mypdf.pdf file
PdfWriter pwriter=PdfWriter.getInstance(doc, new FileOutputStream("phonebook.pdf"));
//open the document so it is ready to write text to the pdf file
doc.open();
//create font objects for table heading column labels to be written to the file
Font fontBoldRed=new Font(FontFamily.TIMES_ROMAN, 20, Font.BOLD, BaseColor.RED);
Font fontBold=new Font(FontFamily.TIMES_ROMAN, 15, Font.BOLD, BaseColor.BLACK);
//create table object that has two columns and two rows
PdfPTable table = new PdfPTable(2);
PdfPCell cell;
cell=new PdfPCell(new Phrase("Phonebook",fontBoldRed));
cell.setColspan(2);
cell.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
table.addCell(cell);
cell=new PdfPCell(new Phrase("Name",fontBold));
table.addCell(cell);
cell=new PdfPCell(new Phrase("Phone",fontBold));
table.addCell(cell);
for(Enumeration<String> e=phonebook.keys(); e.hasMoreElements();){
PhoneBookEntry entry=phonebook.get(e.nextElement());
cell=new PdfPCell(new Phrase(entry.getName()));
table.addCell(cell);
cell=new PdfPCell(new Phrase(entry.getPhone()));
table.addCell(cell);
}
//add table to the document
doc.add(table);
//close the document when writing finishes
doc.close();
displayReport("phonebook.pdf");

}catch(DocumentException de){ de.printStackTrace();}
catch(FileNotFoundException fnfe){fnfe.printStackTrace();}

}
}

//create phonebook html file
public static void createHTML(){

try{
FileWriter fw=new FileWriter("phonebook.html");
BufferedWriter bw=new BufferedWriter(fw);
bw.write("<!Doctype html>");
bw.newLine();
bw.write("<html><head><title>Phone Book</title></head>");
bw.newLine();
bw.write("<body style='padding-left:50px'>");
bw.newLine();
bw.write("<p style='color:#9900ff; font-size:16pt'>Phonebook</p>");
bw.write("<table>");
bw.newLine();
bw.write("<tr style='background-color:#00aaaa'><th>Name</th><th>Phone</th></tr>");
if(phonebook!=null){
Set<String> set=phonebook.keySet();
Iterator<String> iterator=set.iterator();
while(iterator.hasNext()){
PhoneBookEntry cu=phonebook.get(iterator.next());
bw.write("<tr><td>"+cu.getName()+"</td><td>"+cu.getPhone()+"</td></tr>");
bw.newLine();
}

}
bw.write("</table>");
bw.newLine();
bw.write("</body></html>");
bw.flush();
bw.close();
displayReport("phonebook.html");
}catch(IOException ie){ie.printStackTrace();}

}

//display the pdf or html report
public static void displayReport(String src){
try{

if(Desktop.isDesktopSupported()){
File f=new File(src);
Desktop.getDesktop().open(f);

}
}catch(IOException ie){}
}

//This method display options menu
public static void showMenu(){
System.out.println("1. View all phonebook entries");
System.out.println("2. Add to phonebook");
System.out.println("3. Remove from phonebook");
System.out.println("4. Find an entry");
System.out.println("5. Create phonebook pdf file");
System.out.println("6. Create phonebook html file");
System.out.println("7. Exit");
}


}

Best PDF Viewer - Reader on Play Store

5 comments:

  1. That is very nice phonebook It is basic and useful example code.
    Thank for this post...

    ReplyDelete
  2. I have 1 error.., and it says..,

    D:\Franz\PhoneBook17.java:32: error: invalid method declaration; return type required
    PhoneBookEntry(String name,String phone){
    ^
    1 error

    ...What am I going to do..?

    ReplyDelete
  3. Ohh, I have heard about this phonebook program of java before. One of my friend works at essay writing services and he told me about it. But I didn’t know the details of it until I visited this page.

    ReplyDelete
  4. But I didn’t know the details of it until I visited this page.

    ReplyDelete
  5. So many errors how to run this code?

    ReplyDelete