View Javadoc

1   package cz.cuni.amis.utils;
2   
3   import java.io.File;
4   import java.io.FileInputStream;
5   import java.io.FileNotFoundException;
6   import java.io.FileOutputStream;
7   import java.io.IOException;
8   import java.io.InputStream;
9   import java.io.ObjectInputStream;
10  import java.io.ObjectOutputStream;
11  import java.io.OutputStream;
12  
13  public class GenericLoader<T> {
14  	
15  	/**
16  	 * Loads the object of type T from input stream.
17  	 * @param in
18  	 * @return null (failure) || loaded object
19  	 */
20  	public T loadObject(InputStream in) {
21  		try {
22  			return (T) ((new ObjectInputStream(in)).readObject());
23  		} catch (IOException e) {
24  			return null;
25  		} catch (ClassNotFoundException e) {
26  			return null;
27  		}
28  	}
29  	
30  	/**
31  	 * Loads the object of type T from file 'file'.
32  	 * @param file
33  	 * @return null (failure) || loaded object
34  	 */
35  	public T loadObject(File file) {
36  		try {
37  			return loadObject(new FileInputStream(file));
38  		} catch (FileNotFoundException e) {
39  			return null;
40  		}
41  	}
42  	
43  	/**
44  	 * Loads the object of type T from the file at path 'pathAndFileName'.
45  	 * @param pathAndFileName
46  	 * @return null (failure) || loaded object
47  	 */
48  	public T loadObject(String pathAndFileName) {
49  		return loadObject(new File(pathAndFileName));
50  	}
51  	
52  	/**
53  	 * Writes object to the output stream, returns success
54  	 * @param object
55  	 * @param out
56  	 * @return success
57  	 */
58  	public boolean saveObject(T object, ObjectOutputStream out) {
59  		try {
60  			out.writeObject(object);
61  		} catch (IOException e) {
62  			return false;
63  		}
64  		return true;
65  	}
66  	
67  	/**
68  	 * Writes object to the output stream, returns success.
69  	 * @param object
70  	 * @param out
71  	 * @return success
72  	 */
73  	public boolean saveObject(T object, OutputStream out) {
74  		try {
75  			return saveObject(object, new ObjectOutputStream(out));
76  		} catch (IOException e) {
77  			return false;
78  		}
79  	}
80  	
81  	/**
82  	 * Writes object to the file;
83  	 * @param object
84  	 * @param file
85  	 * @return success
86  	 */
87  	public boolean saveObject(T object, File file) {
88  		try {
89  			return saveObject(object, new FileOutputStream(file));
90  		} catch (IOException e) {
91  			return false;
92  		}
93  	}
94  	
95  	/**
96  	 * Writes object to the file at 'pathAndFileName';
97  	 * @param object
98  	 * @param pathAndFileName
99  	 * @return success
100 	 */
101 	public boolean saveObject(T object, String pathAndFileName) {
102 		return saveObject(object, new File(pathAndFileName));
103 	}
104 
105 }