a9018ca066d1cc590fcb92b76ce884919150a1ea
[jvcard.git] / src / be / nikiroo / jvcard / Card.java
1 package be.nikiroo.jvcard;
2
3 import java.io.BufferedReader;
4 import java.io.BufferedWriter;
5 import java.io.File;
6 import java.io.FileReader;
7 import java.io.FileWriter;
8 import java.io.IOException;
9 import java.util.Arrays;
10 import java.util.LinkedList;
11 import java.util.List;
12
13 import be.nikiroo.jvcard.parsers.Format;
14 import be.nikiroo.jvcard.parsers.Parser;
15
16 /**
17 * A card is a contact information card. It contains data about one or more
18 * contacts.
19 *
20 * @author niki
21 *
22 */
23 public class Card {
24 private List<Contact> contacts;
25 private File file;
26 private boolean dirty;
27
28 public Card(File file, Format format) throws IOException {
29 this.file = file;
30
31 BufferedReader buffer = new BufferedReader(new FileReader(file));
32 List<String> lines = new LinkedList<String>();
33 for (String line = buffer.readLine(); line != null; line = buffer
34 .readLine()) {
35 lines.add(line);
36 }
37
38 load(lines, format);
39 }
40
41 public List<Contact> getContacts() {
42 return contacts;
43 }
44
45 public boolean saveAs(File file, Format format) throws IOException {
46 if (file == null)
47 return false;
48
49 BufferedWriter writer = new BufferedWriter(new FileWriter(file));
50 writer.append(toString(format));
51 writer.close();
52
53 if (file.equals(this.file)) {
54 dirty = false;
55 }
56
57 return true;
58 }
59
60 public boolean save(Format format, boolean bKeys) throws IOException {
61 return saveAs(file, format);
62 }
63
64 public String toString(Format format) {
65 return Parser.toString(this, format);
66 }
67
68 public String toString() {
69 return toString(Format.VCard21);
70 }
71
72 protected void load(String serializedContent, Format format) {
73 // note: fixed size array
74 List<String> lines = Arrays.asList(serializedContent.split("\n"));
75 load(lines, format);
76 }
77
78 protected void load(List<String> lines, Format format) {
79 this.contacts = Parser.parse(lines, format);
80 setDirty();
81
82 for (Contact contact : contacts) {
83 contact.setParent(this);
84 }
85 }
86
87 public boolean isDirty() {
88 return dirty;
89 }
90
91 /**
92 * Notify that this element has unsaved changes.
93 */
94 void setDirty() {
95 dirty = true;
96 }
97 }