文件名:test.properties
保存内容:domain=www.test.com
java代码:
package com.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class DomainUtil {
private static DomainUtil util = null;
private static Properties props = null;
private static String PROP_LOCATION = "/test.properties";
private DomainUtil() {
}
public static final DomainUtil getInstance() {
try {
if (util == null) {
loadFile(PROP_LOCATION);
util = new DomainUtil();
}
} catch (IOException e) {
e.printStackTrace();
}
return util;
}
private static void loadFile(String path) throws IOException {
props = new Properties();
InputStream inStream = DomainUtil.class.getResourceAsStream(path);
props.load(inStream);
}
public String getDomainValue(String key) {
if (props == null && props.isEmpty())
return "";
return props.getProperty(key);
}
public static void main(String[] args) {
System.out.println(DomainUtil.getInstance().getDomainValue("domain"));
String appTitle = "app_title";
String appVersion = "app_version";
String appProperties = "app.properties";
Properties settings = new Properties();
settings.put(appTitle, "应用程序标题");
settings.put(appVersion, "1.0");
try {
//写入配置
FileOutputStream out = new FileOutputStream(appProperties);
settings.store(out, "AppConfig");
//读取配置
FileInputStream in = new FileInputStream(appProperties);
settings.load(in);
String title = settings.getProperty(appTitle);
String version = settings.getProperty(appVersion);
System.out.println(title + "\t" + version);
} catch (Exception e) {
e.printStackTrace();
}
}}