package com.properties.test; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class PropertiesUnit { private String filename; private Properties properties; private FileInputStream in; private FileOutputStream out; public PropertiesUnit() { properties = new Properties(); } public PropertiesUnit(String filename) { this.filename = filename; properties = new Properties(); File file = new File(filename); try { in = new FileInputStream(file); properties.load(in); in.close(); } catch (FileNotFoundException e) { System.err.println("配置文件config.properties找不到!"); e.printStackTrace(); } catch (IOException e) { System.err.println("读取配置文件config.properties错误!"); e.printStackTrace(); } } public String getValue(String key) { if(properties.containsKey(key)) { String value = properties.getProperty(key); return value; } else { return ""; } } public String getValue(String fileName,String key) { try { String value=""; in = new FileInputStream(fileName); properties.load(in); in.close(); if(properties.containsKey(key)) { value = properties.getProperty(key); return value; } else { return value; } } catch (FileNotFoundException e) { System.err.println("配置文件config.properties找不到!"); e.printStackTrace(); return ""; } catch (IOException e) { System.err.println("读取配置文件config.properties错误!"); e.printStackTrace(); return ""; } } public void clear() { properties.clear(); } public void setValue(String key,String value) { properties.setProperty(key,value); } public void saveFile(String fileName,String description) { try { out = new FileOutputStream(fileName); properties.store(out,description); out.close(); } catch (FileNotFoundException e) { System.err.println("配置文件config.properties找不到!"); e.printStackTrace(); } catch (IOException e) { System.err.println("读取配置文件config.properties错误!"); e.printStackTrace(); } } public static void main(String[] args) { PropertiesUnit pu = new PropertiesUnit("./config.properties"); String key = pu.getValue("key"); System.out.println(key); } }