-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJournalStorage.java
More file actions
49 lines (43 loc) · 1.68 KB
/
Copy pathJournalStorage.java
File metadata and controls
49 lines (43 loc) · 1.68 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
import java.io.*;
import java.nio.file.*;
import java.time.LocalDateTime;
import java.util.*;
public class JournalStorage {
private final Path storagePath;
public JournalStorage(String filename) {
this.storagePath = Paths.get(filename);
}
public List<JournalEntry> loadEntries() {
List<JournalEntry> entries = new ArrayList<>();
if (!Files.exists(storagePath)) return entries;
try (BufferedReader reader = Files.newBufferedReader(storagePath)) {
String line;
while ((line = reader.readLine()) != null) {
JournalEntry entry = JournalEntry.deserialize(line);
if (entry != null) entries.add(entry);
}
} catch (IOException e) {
System.err.println("Failed to read journal file: " + e.getMessage());
}
return entries;
}
public void saveEntries(List<JournalEntry> entries) {
try (BufferedWriter writer = Files.newBufferedWriter(storagePath)) {
for (JournalEntry entry : entries) {
writer.write(entry.serialize());
writer.newLine();
}
} catch (IOException e) {
System.err.println("Failed to write journal file: " + e.getMessage());
}
}
public int nextId(List<JournalEntry> entries) {
return entries.stream().mapToInt(JournalEntry::getId).max().orElse(0) + 1;
}
public JournalEntry createEntry(List<JournalEntry> entries, String title, String content) {
JournalEntry entry = new JournalEntry(nextId(entries), title, content, LocalDateTime.now());
entries.add(entry);
saveEntries(entries);
return entry;
}
}