Advertisement
Guest User

PropertiesExample.java

a guest
Aug 2nd, 2011
469
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.17 KB | None | 0 0
  1. package com.example;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.util.Properties;
  8.  
  9. class PropertiesExample {
  10.     protected String pathProperties;
  11.     protected Properties properties;
  12.  
  13.     public PropertiesExample(String path) {
  14.         pathProperties = path;
  15.         properties = new Properties();
  16.  
  17.         try {
  18.             FileInputStream stream = new FileInputStream(path);
  19.  
  20.             properties.load(stream);
  21.             stream.close();
  22.         } catch (FileNotFoundException ex) {
  23.             // log warning
  24.         } catch (IOException ex) {
  25.             // log warning
  26.         }
  27.     }
  28.  
  29.     protected <T> T getProperty(String key, T fallback) {
  30.         String value = properties.getProperty(key);
  31.  
  32.         if (value == null) {
  33.             return fallback;
  34.         } else {
  35.             return new T(value);
  36.         }
  37.     }
  38.  
  39.     protected void setProperty(String key, Object value) {
  40.         properties.setProperty(key, value.toString());
  41.  
  42.         try {
  43.             FileOutputStream stream = new FileOutputStream(pathProperties, false);
  44.  
  45.             properties.store(stream, "comment");
  46.             stream.close();
  47.         } catch (FileNotFoundException ex) {
  48.             // log warning
  49.         } catch (IOException ex) {
  50.             // log warning
  51.         }
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement