/**
* ClassName: PropertiesDemo
* @Description: Properties
* properties可以用来做配置文件
*
* ResouceRundle 只读
* Properties 可读可写
* @author cai
* @date 2018年10月18日
*/
public class PropertiesDemo {
public static String version = "";
public static String username = "";
public static String password = "";
//静态代码块,只会执行一次
static {
readConfig();
}
/**
*
* @Description: 对属性文件操作
* @param @param version
* @param @param username
* @param @param password
* @return void
* @throws
*/
private static void writerConfig(String version,String username,String password) {
Properties p = new Properties();
p.put("app.version", version);
p.put("db.username", username);
p.put("db.password", password);
OutputStream out;
try {
out = new FileOutputStream("config.properties");
p.store(out, "update config");
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void readConfig() {
Properties p = new Properties();
InputStream inStream;
try {
inStream = new FileInputStream("config.properties");
p.load(inStream);
version = p.getProperty("app.version");
username = p.getProperty("db.username");
password = p.getProperty("db.password");
inStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
writerConfig("2","cai","2222");
//readConfig(); //此处调用可以用上面的静态代码块来代替
System.out.println(version);
System.out.println(username);
System.out.println(password);
}
}
#update config
#Fri Oct 19 11:58:34 CST 2018
db.password=2222
app.version=2
db.username=cai