Address book that reads and write from a data file - java

I'm doing a small program an addressbook that allows the user to: add contact, search contact and delete contact. All of this data is read and written to .dat file.
Also, how would you create a layout in the data file, (i.e. name, lastname, address and number)?
I'm terrible at Java and I need to get this done.
My code:
public interface Inter
{
//Interface class
public void addContact();
public void deleteContact();
public void searchContact();
public void readFile();
}
public class Contact
{
static String name;
static String lastName;
static String address;
static String number;
public Contact () { }
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader; // reads from dat file
import java.io.FileWriter; // writes from dat file
import java.io.IOException;
import java.io.InputStreamReader;
public class Phonebook extends Contact implements Inter
{
public static void main(String[] args)
{
} // main
#Override
public void deleteContact() { }
#Override
public void searchContact() { }
#Override
public void addContact()
{
String details = null;
System.out.println("Enter new contact i.e name:number:lastname ");
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
try
{
details=in.readLine();
String[] tokens =details.split(":"); // eg david :098:Needham
name= tokens[0];
lastName = tokens[1];
address = tokens[2];
number = tokens[3];
} catch (IOException e1) { }
FileWriter fw = null; // writes contact info to the dat file
try
{
fw = new FileWriter("data.dat");
fw.write(name);
fw.write(lastName);
fw.write(address);
fw.write(number);
} catch (IOException e) { }
BufferedWriter bw = new BufferedWriter(fw);
}
public void readFile() // reads contacts from dat file
{
try
{
BufferedReader in = new BufferedReader(new FileReader("data.dat"));
String str;
while ((str = in.readLine()) != null)
{}
} catch(Exception ex) { }
}
}

Your file format should be a .csv, so it would look like:
name,lastname,address,number,
name,lastname,address,number,
name,lastname,address,number,
I know I shouldn't be posting code for you, but here:
class Contact {
public String name, lastname, address, number;
public Contact(String name, String lastname, String address, String number) {
this.name = name;
this.lastname = lastname;
this.address = address;
this.number = number;
}
public boolean equals(Contact c) {
if(name.equals(c.name) && lastname.equals(c.lastname)
&& address.equals(c.address) && number.equals(c.number))
return true;
return false;
}
public String toString() {
return name+","+lastname+","address+","+number+",";
}
}
public class ContactDriver {
public ArrayList<Contact> contacts = new ArrayList<Contact>();
public static void addContact(Contact c) {
contacts.add(c);
}
public static Contact deleteContact(Contact c) {
return contacts.remove(c);
}
public static int searchContact(Contact c) {
for(int i = 0; i < contacts.size(); i++)
if(contacts.get(i).equals(c))
return i;
return -1;
}
public static void readContacts(String file) throws Exception {
Scanner in = new Scanner(new File(file)).useDelimiter(",");
while(in.hasNextLine()) {
addContact(in.next(), in.next(), in.next(), in.next());
}
}
public static void writeContacts(String fileName) {
FileWriter dest = new FileWriter(fileName);
for(Contact c : contacts)
dest.write(c.toString());
}
public static void main() {
readContacts();
// Do logical stuffs
writeContacts();
}
}
That code is untested, so I'll edit anything that has an error.
Have fun learning more Java!

Related

XMLEncoder not writing object data when class fields are private

I have a class with private fields and public methods. My methods follow the get/set naming convention. When my fields are private and I try to write my object data to an XML file, I get an empty XML file, but when I change them to public, the XML contains all the necessary data. What do you think is causing this?
public class ClassData {
private String name;
private ArrayList<String> methods;
public ClassData()
{
methods = new ArrayList<>();
}
public void setName(String cName)
{
name = cName;
}
public String getName()
{
return name;
}
public void setMethods(String mName)
{
methods.add(mName);
}
public ArrayList<String> getMethods()
{
return methods;
}
}
String fileName = cObj.getName() + ".xml";
XMLEncoder enc=null;
try{
enc=new XMLEncoder(new BufferedOutputStream(new FileOutputStream(fileName)));
}catch(FileNotFoundException fileNotFound){
System.out.println("Unable to save file.");
}
enc.writeObject(cObj);
enc.close();
This is because your methods do not have a "Setter" to make it an accessible "property". Change method setMethods(String mName) to addMethod(String mName) to add individual method and add a setter setMethods that sets same time as that of methods and things work. Sample below:
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
public class ClassData {
private String name;
private ArrayList<String> methods;
public ClassData() {
methods = new ArrayList<>();
}
public void setName(String cName) {
name = cName;
}
public String getName() {
return name;
}
public void addMethod(String mName) {
methods.add(mName);
}
public void setMethods(ArrayList<String> m)
{
methods.addAll(m);
}
public ArrayList<String> getMethods() {
return methods;
}
public static void main(String[] args) {
ClassData cObj = new ClassData();
cObj.setName("This_is_name");
cObj.addMethod("m1");
String fileName = cObj.getName() + ".xml";
XMLEncoder enc = null;
try {
enc = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(fileName)));
} catch (FileNotFoundException fileNotFound) {
System.out.println("Unable to save file.");
}
enc.writeObject(cObj);
enc.close();
}
}

Reading Text file and adding the objects into an Array

I have a Contact class that basically just holds information of a contact. We store the contact object in an array.
I had to write the array into a text file, and I knew how to do that, but now I must read that file and store the objects back into an array, and I'm stuck!
Note, ContactList Below also uses class Contact, which just basically has get/set methods.
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
public class ContactList{
int ptr = -1;
Contact[] list;
int contactLength;
public ContactList(){//second constructor needed
list=new Contact[20];
contactLength=20;
for(int i =0;i<20;i++){
list[i]=null;
}
}
public ContactList(int length){//second constructor needed
list=new Contact[length];
contactLength=length;
for(int i =0;i<length;i++){
list[i]=null;
}
}
public boolean add(Contact c){
boolean found = false;
int i = 0;
while(!found&&i<20){
if (list[i]==null){
list[i]=c;
found=true;
ptr=i;
}
i++;
}
return found;
}
public Contact find(String name){
boolean found=false;
int i =0;
while(i<contactLength&&!found){
ptr++;
if(ptr==contactLength){
ptr=0;
}
if(list[ptr]!=null){
if (list[ptr].getName().contains(name)){
found=true;
return list[ptr];
}
}
i++;
}
return null;
}
public Contact remove(){
Contact current= list[ptr];
list[ptr]=null;
return current;
}
public void displayContacts(){
for(int i =0;i<contactLength;i++){
if(list[i]!=null){
System.out.println(list[i].toString());
}
else {
System.out.println("Empty:");//"Name:\nAddress:\nPhone\nComments:"
}
}
}
public boolean write (String fileName){
PrintWriter p = null;
try {
p = new PrintWriter(new File(fileName));
} catch (Exception e) {
return false;
}
for(int i =0;i<contactLength;i++){
if(list[i]!=null){
p.println(list[i].toString());
}}
p.close();
return true;
}
public class Contact {
private String name;
private long phone;
private String address;
private String comments;
public void setName( String name){
this.name =name;
}
public String getName(){
return name;
}
public void setPhone(long phone){
this.phone=phone;
}
public long getPhone(){
return phone;
}
public void setAddress(String address){
this.address= address;
}
public String getAddress(){
return address;
}
public void setComments( String comments){
this.comments= comments;
}
public String getComments(){
return comments;
}
public String toString(){
return ("Name:\t\t"+name+"\nAddress:\t"+address+"\nPhone Number:\t"+phone+"\nComments:\t"+comments +"\n");
}
public Contact(String name, long phone, String address, String comments){
this.name=name;
this.phone=phone;
this.address=address;
this.comments=comments;
}
public boolean equals(Contact other){
if (this.name!=other.name){
return false;
}
if (this.phone!=other.phone){
return false;
}
if (this.address!=other.address){
return false;
}
if (this.comments!=other.comments){
return false;
}
return true;
}
Here is what I have so far...
public boolean read(String fileName){
Scanner s = null;
try {
s = new Scanner(new File(fileName));
} catch (Exception e) { // returns false if fails to find fileName
return false;
}
for(int i=0; i)
}
And YES I must use array! No lists! And nothing fancy please, this is an intro class, I won't understand it. Just scanner.
I see the pros and cons in the comment section, what about putting an end to the debate, given how you write I'm guessing you will need something like:
public static void read(String fileName){
try(BufferedReader in = new BufferedReader(new FileReader(fileName))){
String line = null;
String[] contact = new String[4];
int contactCounter = 0;
int buffer = 0;
while ((line = in.readLine()) != null){
buffer = line.split("\t").length - 1;
contact[contactCounter] = line.split("\t")[buffer];
contactCounter++;
if (contactCounter == 3){
new Contact(contact[0], contact[1], contact[2], contact[3]);
contactCounter == 0;
}
}
} catch (IOException e){
e.printStackTrace();
}
}
I strongly suggest you improve how you serialize your Contact because this format is a mess, especially having not clear boundaries, the best I could figure was counting 4 EOL to create a new Contact.
Maybe have a look at csv format: https://en.wikipedia.org/wiki/Comma-separated_values

Java - Type Mismatch: Cannot Convert From Element type String[] to List<String>

I'm unfamiliar with getters and setters (and basically just Java) but I have to use them for this assignment, so if I did anything wrong with those please tell me.
The more important issue is the error that I am getting on my method. The word for word instructions from my assignment for the particular method I'm working on are:
Your processData() method should take all the record data from your ArrayList and add the data into each of your instance fields via your setters.
But I keep getting an error that says:
Type mismatch: cannot convert from element type String[] to List
On the line that says "for (List<String> rowData: content)" on the word content.
Thank you very much for any help you can give me.
My code so far:
public abstract class Client {
String file = "bank-Detail.csv";
ArrayList<String[]> bank = new ArrayList<>();
static Client o[] = new Client[12];
public Client(String file) {
this.file = file;
}
private String ID;
private String Age;
private String Sex;
private String Region;
private String Income;
private String Married;
private String Children;
private String Car;
private String Save_Act;
private String Current_Act;
private String Mortgage;
private String Pep;
public List<String[]> readData() throws IOException {
//initialize variable
int count = 0;
//name file
String file = "bank-Detail.txt";
//make array list
List<String[]> content = new ArrayList<>();
//trycatch for exceptions
try {
//file reader
BufferedReader br = new BufferedReader(new FileReader(file));
//string to add lines to
String line = "";
while ((line = br.readLine()) != null) {
content.add(line.split(","));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
processData(content);
return content;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getAge() {
return Age;
}
public void setAge(String age) {
this.Age = age;
}
public String getSex() {
return Sex;
}
public void setSex(String sex) {
Sex = sex;
}
public String getRegion() {
return Region;
}
public void setRegion(String region) {
Region = region;
}
public String getIncome() {
return Income;
}
public void setIncome(String income) {
Income = income;
}
public String getMarried() {
return Married;
}
public void setMarried(String married) {
Married = married;
}
public String getChildren() {
return Children;
}
public void setChildren(String children) {
Children = children;
}
public String getCar() {
return Car;
}
public void setCar(String car) {
Car = car;
}
public String getSave_Act() {
return Save_Act;
}
public void setSave_Act(String save_Act) {
Save_Act = save_Act;
}
public String getCurrent_Act() {
return Current_Act;
}
public void setCurrent_Act(String current_Act) {
this.Current_Act = current_Act;
}
public String getMortgage() {
return Mortgage;
}
public void setMortgage(String mortgage) {
this.Mortgage = mortgage;
}
public String getPep() {
return Pep;
}
public void setPep(String pep) {
Pep = pep;
}
public String toString() {
return "[ID = " + ", age=";
/// ect....
}
public void processData(List<String[]> content) {
int index = 0;
for (List<String> rowData : content) {
//initialize array of objects
//o[index] = new Client();
//use setters to populate your array of objects
o[index].setID(rowData.get(0));
o[index].setAge(rowData.get(1));
o[index].setRegion(rowData.get(3));
o[index].setSex(rowData.get(2));
o[index].setIncome(rowData.get(4));
o[index].setMarried(rowData.get(5));
o[index].setChildren(rowData.get(6));
o[index].setCar(rowData.get(7));
o[index].setSave_Act(rowData.get(8));
o[index].setCurrent_Act(rowData.get(9));
o[index].setMortgage(rowData.get(10));
o[index].setPep(rowData.get(11));
System.out.println(rowData);
index++;
}
}
public void printData() {
}
}
The problem is in the processData method. The type of content is List<String[]>. So when you try to loop this list, each element is a String array, not List. Also, since each element in your list is a String array, you can access the elements of each of the String Array elements of the list by using the normal array square brackets, instead of get method of List. Try the following fix:
public void processData(List<String[]> content) {
int index=0;
for (String[] rowData: content){
//initialize array of objects
//o[index] = new Client();
//use setters to populate your array of objects
o[index].setID(rowData[0]);
o[index].setAge(rowData[1]);
o[index].setRegion(rowData[3]);
o[index].setSex(rowData[2]);
o[index].setIncome(rowData[4]);
o[index].setMarried(rowData[5]);
o[index].setChildren(rowData[6]);
o[index].setCar(rowData[7]);
o[index].setSave_Act(rowData[8]);
o[index].setCurrent_Act(rowData[9]);
o[index].setMortgage(rowData[10]);
o[index].setPep(rowData[11]);
System.out.println(rowData);
index++;
}
}
As your error hints at... content is a List<String[]>, so it contains String[] elements, not List<String> elements.
If your end goal is a list of Client objects, just make the method List<Client> readData() instead.
List<Client> clients = new ArrayList<Client>();
BufferedReader br = null;
try {
//file reader
br = new BufferedReader(new FileReader(file));
//string to add lines to
String line = "";
Client c = null;
while ((line = br.readLine()) != null) {
c = new Client();
String[] rowData = line.split(",");
c.setID(rowData.get(0));
...
clients.add(c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (Exception e) {}
}
return clients;

How does one pass a class through an array and then fill the array with a txt document

So... My goal here to run this class through an array then fill the array with a .txt document with 43 instances which I will then take user data and compare the two to find an ideal match. I should note that this is for a seating plan -
The text document looks like so -
01 STANDARD True False True F False
public class Seat {
private String eMail = "";
private int number;
private String type;
private boolean window;
private boolean aisle;
private boolean table;
private String f;
private String b;
private boolean ease;
public Seat(int number, String type, boolean window, boolean aisle, boolean table, String f, String b, boolean ease) {
this.number = number;
this.type = type;
this.window = window;
this.aisle = aisle;
this.table = table;
this.f = f;
this.b = b;
this.ease = ease;
}
public String geteMail() {
return eMail;
}
public void seteMail(String eMail) {
this.eMail = eMail;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isWindow() {
return window;
}
public void setWindow(boolean window) {
this.window = window;
}
public boolean isAisle() {
return aisle;
}
public void setAisle(boolean aisle) {
this.aisle = aisle;
}
public boolean isTable() {
return table;
}
public void setTable(boolean table) {
this.table = table;
}
public String getF() {
return f;
}
public void setF(String f) {
this.f = f;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
public boolean isEase() {
return ease;
}
public void setEase(boolean ease) {
this.ease = ease;
}
}
public class Driver {
static Scanner S = new Scanner(System.in);
public static void main(String[] args) throws FileNotFoundException {
Scanner inFile = new Scanner(new File("//Users//Mike//Desktop//Seats-2.txt"));
String reservation = inFile.nextLine();
Seat seat [] = new Seat [43];
//while (inFile.hasNextLine()){
//for(int i = 0; i <= reservation.length(); i++){
//System.out.println(reservation.toString(seat));
//}
//}
I've tried methods such as equals(reservation.toString()) how ever these won't work due to the array being built from the Class Seat.
Any guidance will be very helpful.
I'm not looking for easy fix, just some guidance on where to look.
Thank you
If the text file is small, let's just read it whole in a String
public static String ReadWholeFile(String filename) throws IOException
{
final File file = new File(filename);
final FileInputStream fis = new FileInputStream(file);
final byte[] data = new byte[(int)file.length()];
fis.read(data);
fis.close();
return new String(data, "UTF-8");
}
And then parse line by line, converting in Seats
public List<Seat> getSeats(String filename) throws IOException {
final String[] lines = ReadWholeFile(filename).split("\n");
final List<Seat> ret = new ArrayList<Seat>();
for (int i=0; i<lines.length; i++)
try {
final String[] parts = lines[i].split("\\s"); // split on whitespaces
final int num = Integer.parseInt(parts[0]);
ret.add(new Seat(num, parts[1], isTrue(parts[2]), isTrue(parts[3]), isTrue(parts[4]), isTrue(parts[5]), isTrue(parts[6]));
}
catch (Exception e) { /* whatever */ }
return ret;
}
Strings that mean true are "T", "true", ...? If that's the case:
public static isTrue(String x) {
return x.startsWith("T") || x.startsWith("t");
}
if you really don't want to read the whole file, you could go with:
public static List<Seat> getSeats2(String filename) {
final List<Seat> ret = new ArrayList<Seat>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filename));
String line;
while (line = br.readLine()) {
final String[] parts = line.split("\\s"); // split on whitespaces
// as above
}
}
catch (Exception e) { /* handle errors */ }
finally {
if (br != null)
try { br.close(); }
catch (Exception e) {}
}
return res;
}

Delete row in a CSV file and export file in JAVA

I have a program in which I read a CSV file and export a text file type.
CSV attributes are name, date of birth, email and address.
I need a BufferedReader through a user can insert the email of one of the records and delete the entire row in the CSV (deleting name, date of birth, and email address) and re-export the text file type.
I do not have much knowledge of Java so much that could help me guide me to the solution.
I share the code,
Help is appreciated,
Thank you!
public class Personas {
private String nombre;
private String fechaNacimiento;
private String email;
private String direccion;
public Personas(String nombre, String fechaNacimiento, String email,
String direccion) {
super();
this.nombre = nombre;
this.fechaNacimiento = fechaNacimiento;
this.email = email;
this.direccion = direccion;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getFechaNacimiento() {
return fechaNacimiento;
}
public void setFechaNacimiento(String fechaNacimiento) {
this.fechaNacimiento = fechaNacimiento;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
}
Here is the main class
import java.io.*;
public class Principal {
public static void main(String[] args) {
// TODO Auto-generated method stub
Personas[] miLista = new Personas[100];
int i = 0;
String texto = "";
FileReader lector;
try {
lector = new FileReader("C:\\Users\\CD\\Downloads\\dummydata.csv");
BufferedReader contenido=new BufferedReader(lector);
try {
while((texto=contenido.readLine())!=null){
String[] valores = texto.split(",");
Personas persona = new Personas(valores[0], valores[1], valores[2], valores[3]);
miLista[i]=persona;
i++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("hay mas de 100 registros en el archivo");
System.out.println("solo se cargaran los primeros 100");
}catch(Exception e){
System.out.println("error desconocido contacte con el desarrollador...");
System.out.println(e.getMessage());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
System.out.print("El archivo no se encuentra...");
}catch(Exception e){
System.out.println("error desconocido contacte con el desarrollador...");
System.out.println(e.getMessage());
}
for (Personas persona : miLista) {
System.out.print(persona.getNombre());
System.out.print(persona.getDireccion());
System.out.print(persona.getFechaNacimiento());
System.out.println(persona.getEmail());
}
File miArchivo = new File("miNuevoArchivo.txt");
try{
FileWriter fw = new FileWriter(miArchivo);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter wr = new PrintWriter(bw);
for (Personas persona : miLista) {
wr.write(persona.getNombre()+"\t");
wr.append(persona.getFechaNacimiento()+"\t");
wr.append(persona.getDireccion()+"\t");
wr.println(persona.getEmail());
}
wr.close();
bw.close();
}catch(IOException e){
System.out.println(e.getMessage());
}
}
}
I hope it help... but not sure it's what you want to do.
Try to not mix differents languages, see try-with-resource, use List (ArrayList) instead of Arrays, create simple functions and read some docs about iterator.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class Principal {
private static final String IN = "C:\\Users\\CD\\Downloads\\dummydata.csv";
private static final String OUT = "C:\\Users\\CD\\Downloads\\result.txt";
public static List<Personas> readFile(final String file) throws Exception {
final List<Personas> result = new ArrayList<Personas>();
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String texto = "";
while ((texto = reader.readLine()) != null) {
final String[] valores = texto.split(",");
final Personas persona = new Personas(valores[0], valores[1], valores[2], valores[3]);
result.add(persona);
}
}
return result;
}
public static void write(final String file, final List<Personas> personas) throws Exception {
new File(file);
try (PrintWriter wr = new PrintWriter(new File(file))) {
for (final Personas persona : personas) {
wr.write(persona.getNombre() + "\t");
wr.append(persona.getFechaNacimiento() + "\t");
wr.append(persona.getDireccion() + "\t");
wr.println(persona.getEmail());
}
}
}
public static void main(final String[] args) throws Exception {
final List<String> emailsToRemove = Arrays.asList("email1#lol.com", "email2#lol.com");
final List<Personas> personas = readFile(IN);
//Remove some personnas
for (Iterator<Personas> it = personas.iterator(); it.hasNext(); /**RIEN**/) {
Personas act = it.next();
if(emailsToRemove.contains(act.getEmail())){
it.remove();
}
}
write(OUT, personas);
}
}

Categories