-
Notifications
You must be signed in to change notification settings - Fork 203
Expand file tree
/
Copy pathSavedList.java
More file actions
67 lines (57 loc) · 1.75 KB
/
SavedList.java
File metadata and controls
67 lines (57 loc) · 1.75 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
package com.example.task02;
import java.io.*;
import java.nio.file.Files;
import java.util.AbstractList;
import java.util.ArrayList;
import java.util.List;
public class SavedList<E extends Serializable> extends AbstractList<E> {
private final File file;
private final List<E> list = new ArrayList<>();
public SavedList(File file) {
this.file = file;
loadFromFile();
}
private void loadFromFile() {
if (!file.exists()) return;
try (ObjectInputStream stream = new ObjectInputStream(Files.newInputStream(file.toPath()))) {
@SuppressWarnings("unchecked")
List<E> loadedList = (ArrayList<E>) stream.readObject();
list.clear();
list.addAll(loadedList);
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException("Error downloading data from a file", e);
}
}
private void saveToFile() {
try (ObjectOutputStream stream = new ObjectOutputStream(Files.newOutputStream(file.toPath()))) {
stream.writeObject(list);
} catch (IOException e) {
throw new RuntimeException("Error saving data to file", e);
}
}
@Override
public E get(int index) {
return list.get(index);
}
@Override
public E set(int index, E element) {
E oldElement = list.set(index, element);
saveToFile();
return oldElement;
}
@Override
public int size() {
return list.size();
}
@Override
public void add(int index, E element) {
list.add(index, element);
saveToFile();
}
@Override
public E remove(int index) {
E removedElement = list.remove(index);
saveToFile();
return removedElement;
}
}