操纵properties文件

 定义个 config.properties 文件,里边的内容如下

fileserver.filePath=D\:/test

dwrservice.xmlExchangeLoadPath=/exchange/fromOuter/
dwrservice.xmlExchangeExportPath=/exchange/toOuter/

ftp.ipaddress=10.92.201.214
ftp.username=wangzha
ftp.password=123456
ftp.workingDirectory=/

mail.serverIp=192.168.1.205
[email protected]
mail.serverPort=25
mail.apiServerPort=6195

 

 

再写个 Java 工作类

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;


public class Configuration {

	private static Configuration configuration = null;
	private String path = "";
	private Map map = null;

	/**
	 * 
	 */
	private Configuration() {
		try {
			this.path = this.getClass().getResource("/").getPath()
					+ "config.properties";
			InputStream in = this.getClass().getClassLoader().getResourceAsStream("config.properties");
			map = this.readProperties(in);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Configuration newInstance() {
		if (configuration == null) {
			configuration = new Configuration();
		}
		return configuration;
	}

	public int setProperty(String key, String value) {
		Properties props = new Properties();
		int num = 0;
		InputStream in = null;
		OutputStream out = null;
		try {
			in = new FileInputStream(this.path);
			props.load(in);
			in.close();
			out = new FileOutputStream(this.path);
			props.setProperty(key, value);
			props.store(out, "setProperty");
		} catch (Exception ex) {
			ex.printStackTrace();
			num = 1;
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (Exception ex) {
				ex.printStackTrace();
				num = 1;
			}
		}
		return num;
	}

	public String getProperty(String key) {
		String value = "";
		value = (String) this.map.get(key);
		if (value == null) {
			value = "";
		}
		return value;
	}

	public String getProperty(String key, String defValue) {
		String value = "";
		value = (String) this.map.get(key);
		if (value == null || value.equals("")) {
			value = defValue;
		}
		return value;
	}

	public Map readProperties(InputStream in) {
		
		Properties props = new Properties();
		Map map = new HashMap();
		String key = "";
		String value = "";
		try {
			props.load(in);
			Enumeration en = props.propertyNames();
			while (en.hasMoreElements()) {
				key = (String) en.nextElement();
				value = props.getProperty(key);
				map.put(key, value);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != in) {
					in.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return map;
	}

}

 

 

使用实例

String filePath = Configuration.newInstance().getProperty(
				"fileserver.filePath");

 

你可能感兴趣的:(java,工作,Exchange)