forked from Ghosh-Anisha/OOAD---Version-Control-System
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SerializeUtils.java
68 lines (61 loc) · 2.18 KB
/
SerializeUtils.java
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
import java.io.*;
public class SerializeUtils {
public static void storeObjectToFile(Object obj, String filePath) {
File outFile = new File(filePath);
try {
ObjectOutputStream out =
new ObjectOutputStream(new FileOutputStream(outFile));
out.writeObject(obj);
out.close();
} catch (IOException excp) {
System.out.println("Error storing object to file.");
}
}
public static byte[] toByteArray(Object obj) {
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
ObjectOutputStream objectStream = new ObjectOutputStream(stream);
objectStream.writeObject(obj);
objectStream.close();
return stream.toByteArray();
} catch (IOException excp) {
throw new IllegalArgumentException("Internal error serializing commit.");
}
}
public static <T> T deserialize(String fileName, Class<T> type) {
T obj;
File inFile = new File(fileName);
try {
ObjectInputStream inp =
new ObjectInputStream(new FileInputStream(inFile));
obj = (T) inp.readObject();
inp.close();
} catch (IOException | ClassNotFoundException excp) {
obj = null;
}
return obj;
}
public static void writeStringToFile(String text, String filepath, boolean appending) {
try {
File logFile = new File(filepath);
BufferedWriter out = new BufferedWriter(new FileWriter(logFile, appending));
out.write(text);
out.close();
} catch (IOException excp) {
return;
}
}
public static String readStringFromFile(String filepath) {
File readingFrom = new File(filepath);
try (BufferedReader br = new BufferedReader(new FileReader(readingFrom))) {
String line = null;
String everything = "";
while ((line = br.readLine()) != null) {
everything += line;
}
return everything;
} catch (IOException excp) {
return "error";
}
}
}