-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileItem.java
More file actions
70 lines (56 loc) · 1.9 KB
/
FileItem.java
File metadata and controls
70 lines (56 loc) · 1.9 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
package AllFiles;
import java.io.*;
import javax.swing.JOptionPane;
public class FileItem<T>
{
private String fileName;
private File file;
public FileItem(String fileName)
{
this.fileName = fileName;
}
public void saveToFile(T list)
{
this.file = new File(fileName);
//Try to save list to file.
try
{
if(!file.exists())
file.createNewFile();
FileOutputStream FOS = new FileOutputStream(file);
ObjectOutputStream OOS = new ObjectOutputStream(FOS);
OOS.writeObject(list); //Put the entire list in the ObjectOutputStream,
//which then saves the list to file thanks to FileOutputStream.
OOS.close();
FOS.close();
}
catch(Exception e)
{
//The list could, for whatever reason, not be saved.
JOptionPane.showMessageDialog(null, "Is wasn't possible to save the file!", "Error message", JOptionPane.ERROR_MESSAGE);
}
}
public T loadFromFile()
{
T list = null;
this.file = new File(fileName);
//Try to load the list from the file.
try
{
if(file.exists())
{
FileInputStream FIS = new FileInputStream(file);
ObjectInputStream OIS = new ObjectInputStream(FIS);
list = (T)OIS.readObject(); //Put the list in the file to the ArrayList<Media> called "list".
OIS.close();
FIS.close();
}
}
catch(Exception e)
{
//The file could, for whatever reason, not be read.
JOptionPane.showMessageDialog(null, "Is wasn't possible to load the file!", "Error message", JOptionPane.ERROR_MESSAGE);
}
return list;
}
}