Subversion Repositories SmartDukaan

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
17 naveen 1
/**
2
 * 
3
 */
4
package in.shop2020.metamodel.util;
5
 
18 naveen 6
import in.shop2020.util.Utils;
7
 
17 naveen 8
import java.io.File;
9
import java.io.FileInputStream;
10
import java.io.FileOutputStream;
11
import java.io.ObjectInputStream;
12
import java.io.ObjectOutputStream;
13
 
14
/**
49 naveen 15
 * Utility functions to store and retrieve serialised objects
16
 * 
17 naveen 17
 * @author naveen
18
 *
19
 */
20
public class DBUtils {
18 naveen 21
 
17 naveen 22
	/**
49 naveen 23
	 * Serialises object into given file
17 naveen 24
	 * 
49 naveen 25
	 * @param objectToStore Object to store
26
	 * @param dbFile File to use
18 naveen 27
	 * @throws Exception
17 naveen 28
	 */
18 naveen 29
	public static void store(Object objectToStore, String dbFile) 
30
		throws Exception {		
21 naveen 31
		File f = new File(dbFile);
32
		if(!f.exists()) {
33
			f.createNewFile();
34
		}
35
 
49 naveen 36
		ObjectOutputStream out = null;
37
		try {
38
			FileOutputStream fos = new FileOutputStream(f);
39
			out = new ObjectOutputStream(fos);
40
 
41
			out.writeObject(objectToStore);
42
		}
43
		finally {
44
			if(out != null) {
45
				out.close();
46
			}
47
		}
41 naveen 48
		Utils.info("Serialization complete");
17 naveen 49
	}
50
 
51
	/**
49 naveen 52
	 * Retrieves serialised object from given file
17 naveen 53
	 * 
18 naveen 54
	 * @param dbFile
49 naveen 55
	 * @return De-serialised object
18 naveen 56
	 * @throws Exception
17 naveen 57
	 */
58
	public static Object read(String dbFile) throws Exception {
43 naveen 59
 
21 naveen 60
		File f = new File(dbFile);
61
		if(!f.exists()) {
43 naveen 62
			Utils.severe(dbFile + " - does not exist");
21 naveen 63
			return null;
64
		}
65
 
49 naveen 66
		Object obj = null;
67
		ObjectInputStream in = null;
68
		try {
69
			FileInputStream fis = new FileInputStream(f);
70
			in = new ObjectInputStream(fis);
71
			obj = in.readObject();
72
		}
73
		finally {
74
			if(in != null) {
75
				in.close();
76
			}
77
		}
17 naveen 78
 
42 naveen 79
		Utils.info("De-serialization complete");
17 naveen 80
		return obj;
81
	}
82
}