KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tonbeller > tbutils > res > FilePersistentResourceProvider


1 package com.tonbeller.tbutils.res;
2
3 import java.io.File JavaDoc;
4 import java.io.FileInputStream JavaDoc;
5 import java.io.FileOutputStream JavaDoc;
6 import java.io.IOException JavaDoc;
7 import java.io.InputStream JavaDoc;
8 import java.io.OutputStream JavaDoc;
9 import java.util.Collection JavaDoc;
10 import java.util.Properties JavaDoc;
11
12 import org.apache.log4j.Logger;
13
14 /**
15  * A ResourceProvider that allows to store name/value pairs in the filesystem.
16  * @author av
17  *
18  * @since 18.01.2005
19  */

20 class FilePersistentResourceProvider implements PersistentResourceProvider {
21   Properties JavaDoc props;
22   File JavaDoc file;
23
24   private static Logger logger = Logger.getLogger(FilePersistentResourceProvider.class);
25
26   public FilePersistentResourceProvider(File JavaDoc file) {
27     this.file = file;
28     load();
29   }
30
31   private void load() {
32     props = new Properties JavaDoc();
33     InputStream JavaDoc is = null;
34     try {
35       if (!file.exists())
36         return;
37       is = new FileInputStream JavaDoc(file);
38       props.load(is);
39     } catch (IOException JavaDoc e) {
40       logger.error(null, e);
41     } finally {
42       if (is != null) {
43         try {
44           is.close();
45         } catch (IOException JavaDoc e) {
46           logger.error(null, e);
47         }
48       }
49     }
50   }
51
52   private void store() {
53     OutputStream JavaDoc os = null;
54     try {
55       os = new FileOutputStream JavaDoc(file);
56       props.store(os, "## TONBELLER");
57     } catch (IOException JavaDoc e) {
58       logger.error(null, e);
59     } finally {
60       if (os != null) {
61         try {
62           os.close();
63         } catch (IOException JavaDoc e1) {
64           logger.error(null, e1);
65         }
66       }
67     }
68
69   }
70
71   public String JavaDoc getString(String JavaDoc key) {
72     return props.getProperty(key);
73   }
74
75   public void store(String JavaDoc key, String JavaDoc value) {
76     props.setProperty(key, value);
77   }
78
79   public void remove(String JavaDoc key) {
80     props.remove(key);
81   }
82
83   public Collection JavaDoc keySet() {
84     return props.keySet();
85   }
86
87   public void flush() {
88     store();
89   }
90
91   public void close() {
92     store();
93   }
94
95   public void dump(Dumper d) {
96     d.dump(this);
97   }
98
99   public String JavaDoc getName() {
100     return "FileResouceProvider " + file;
101   }
102 }
Popular Tags