1 6 7 package org.jfox.persistent; 8 9 import java.io.File ; 10 import java.io.FileInputStream ; 11 import java.io.FileOutputStream ; 12 import java.io.IOException ; 13 import java.io.ObjectInputStream ; 14 import java.io.ObjectOutputStream ; 15 import java.io.Serializable ; 16 import java.util.Date ; 17 18 import org.jfox.ioc.Component; 19 import org.jfox.ioc.ComponentContext; 20 21 22 25 26 public class FilePersistenter implements Persistenter, Component { 27 28 private String directory = "."; 29 30 public FilePersistenter() { 31 32 } 33 34 public FilePersistenter(String directory) { 35 this.directory = directory; 36 } 37 38 public synchronized Object load(Object identity) throws Exception { 39 if(identity == null) throw new IllegalArgumentException ("identity can not be null."); 40 41 Object result = null; 42 ObjectInputStream ois = null; 43 File file = null; 44 try { 45 String filename = getFullFileName(identity); 46 file = new File (filename); 47 ois = new ObjectInputStream (new FileInputStream (file)); 48 result = ois.readObject(); 49 } 50 catch(Exception e) { 51 throw e; 52 } 53 finally { 54 try { 55 ois.close(); 56 if(file != null) { 57 file.delete(); 58 } 59 } 60 catch(IOException e) { 61 } 62 } 63 return result; 64 } 65 66 public synchronized void store(Object identity, Serializable data) throws Exception { 68 if(identity == null || data == null) throw new IllegalArgumentException ("identity and data can not be null."); 69 String filename = getFullFileName(identity); 70 ObjectOutputStream oos = null; 71 try { 72 oos = new ObjectOutputStream (new FileOutputStream (filename)); 73 oos.writeObject(data); 74 } 75 catch(Exception e) { 76 throw e; 77 } 78 finally { 79 try { 80 oos.close(); 81 } 82 catch(IOException e) { 83 e.printStackTrace(); 84 } 85 } 86 } 87 88 public boolean remove(Object identity) { 89 if(identity == null) throw new IllegalArgumentException ("identity can not be null."); 90 try { 91 String filename = getFullFileName(identity); 92 File file = new File (filename); 93 return file.delete(); 94 } 95 catch(Exception e) { 96 e.printStackTrace(); 97 return false; 98 } 99 100 } 101 102 private String getFullFileName(Object identity) { 103 return directory + File.separator + identity.toString() + ".ser"; 104 } 105 106 107 public void setComponentContext(ComponentContext ctx) { 108 directory = ctx.getModuleDir() + File.separator + "temp"; 109 } 110 111 public static void main(String [] args) throws Exception { 112 Date date = new Date (); 113 FilePersistenter fp = new FilePersistenter(); 114 String identity = "test"; 115 fp.store(identity, date); 116 Date serDate = (Date ) fp.load(identity); 117 System.out.println(serDate.toString()); 118 } 119 120 } 121 122 123 | Popular Tags |