-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContactRepository.java
More file actions
96 lines (83 loc) · 2.82 KB
/
ContactRepository.java
File metadata and controls
96 lines (83 loc) · 2.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import java.io.*;
import java.util.*;
public class ContactRepository {
private Map<String, Contact> contacts;
private static final String DATA_FILE = "contacts.dat";
private int nextId;
public ContactRepository() {
contacts = new HashMap<>();
nextId = 1;
loadContacts();
}
public String generateId() {
return "C" + String.format("%04d", nextId++);
}
public void addContact(Contact contact) {
contacts.put(contact.getId(), contact);
saveContacts();
}
public Contact getContact(String id) {
return contacts.get(id);
}
public List<Contact> getAllContacts() {
return new ArrayList<>(contacts.values());
}
public boolean updateContact(String id, Contact updatedContact) {
if (contacts.containsKey(id)) {
contacts.put(id, updatedContact);
saveContacts();
return true;
}
return false;
}
public boolean deleteContact(String id) {
if (contacts.remove(id) != null) {
saveContacts();
return true;
}
return false;
}
public List<Contact> searchByName(String name) {
List<Contact> results = new ArrayList<>();
String lowerName = name.toLowerCase();
for (Contact contact : contacts.values()) {
if (contact.getName().toLowerCase().contains(lowerName)) {
results.add(contact);
}
}
return results;
}
public List<Contact> searchByPhone(String phone) {
List<Contact> results = new ArrayList<>();
for (Contact contact : contacts.values()) {
if (contact.getPhone().contains(phone)) {
results.add(contact);
}
}
return results;
}
private void saveContacts() {
try (ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(DATA_FILE))) {
oos.writeObject(contacts);
oos.writeInt(nextId);
} catch (IOException e) {
System.err.println("Error saving contacts: " + e.getMessage());
}
}
@SuppressWarnings("unchecked")
private void loadContacts() {
File file = new File(DATA_FILE);
if (file.exists()) {
try (ObjectInputStream ois = new ObjectInputStream(
new FileInputStream(DATA_FILE))) {
contacts = (Map<String, Contact>) ois.readObject();
nextId = ois.readInt();
} catch (IOException | ClassNotFoundException e) {
System.err.println("Error loading contacts: " + e.getMessage());
contacts = new HashMap<>();
nextId = 1;
}
}
}
}