1 package org.properties.util; 2 3 import java.io.FileInputStream; 4 import java.io.FileOutputStream; 5 import java.io.IOException; 6 import java.io.InputStream; 7 import java.io.OutputStream; 8 import java.util.Properties; 9 10 11 public class PropertiesUtil { 12 // 文件名 13 private String properiesName = ""; 14 15 // 构造方法 16 public PropertiesUtil() { 17 18 } 19 public PropertiesUtil(String fileName) { 20 this.properiesName = fileName; 21 } 22 23 // 根据配置文件的key取值 24 public String readProperty(String key) { 25 String value = ""; 26 InputStream is = null; 27 try { 28 is = PropertiesUtil.class.getClassLoader().getResourceAsStream( 29 properiesName); 30 Properties p = new Properties(); 31 p.load(is); 32 value = p.getProperty(key); 33 } catch (IOException e) { 34 // TODO Auto-generated catch block 35 e.printStackTrace(); 36 } finally { 37 try { 38 is.close(); 39 } catch (IOException e) { 40 // TODO Auto-generated catch block 41 e.printStackTrace(); 42 } 43 } 44 return value; 45 } 46 47 // 取全部内容 48 public Properties getProperties() { 49 Properties p = new Properties(); 50 InputStream is = null; 51 try { 52 is = PropertiesUtil.class.getClassLoader().getResourceAsStream( 53 properiesName); 54 p.load(is); 55 } catch (IOException e) { 56 // TODO Auto-generated catch block 57 e.printStackTrace(); 58 } finally { 59 try { 60 is.close(); 61 } catch (IOException e) { 62 // TODO Auto-generated catch block 63 e.printStackTrace(); 64 } 65 } 66 return p; 67 } 68 69 // 根据键值取 70 public void writeProperty(String key, String value) { 71 InputStream is = null; 72 OutputStream os = null; 73 Properties p = new Properties(); 74 try { 75 is = new FileInputStream(properiesName); 76 p.load(is); 77 os = new FileOutputStream(PropertiesUtil.class.getClassLoader().getResource(properiesName).getFile()); 78 79 p.setProperty(key, value); 80 p.store(os, key); 81 os.flush(); 82 os.close(); 83 } catch (Exception e) { 84 // TODO Auto-generated catch block 85 e.printStackTrace(); 86 } finally { 87 try { 88 if (null != is) 89 is.close(); 90 if (null != os) 91 os.close(); 92 } catch (IOException e) { 93 // TODO Auto-generated catch block 94 e.printStackTrace(); 95 } 96 } 97 98 } 99 100 101 102 }