假如有一些固定的属性像版本号,ip地址号,我想修改其中的属性,但是项目一旦发布后就得从第一步开始修改,每次都得经历编写-->打包-->发布的过程,很麻烦,配置文件很好的解决这个问题。
package io_12_properties;
import java.io.*;
import java.util.Properties;
/**
* ResourceBundle只可读,不可写
* Properties 可读可写
*/
public class demo {
public static String version = "";
public static String name = "";
public static String pwd = "";
//静态代码块,只执行一次,先执行
// static {
// readConfig();
// }
/**
* 读取配置文件
*/
public static void readConfig(){
Properties properties = new Properties();
try {
//如果想将配置文件放到指定的文件中---通过当前线程的类加载器来加载指定包下的配置文件
// InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("io_12_properties/test.properties");
InputStream inputStream = new FileInputStream("test.properties");
properties.load(inputStream);
//从Properties中获取数据
version = properties.getProperty("app.version");
name = properties.getProperty("db.name");
pwd = properties.getProperty("db.pwd");
//关闭流
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 写入配置文件
*/
public static void writeConfig(String version ,String name, String pwd){
Properties properties = new Properties();
properties.put("app.version",version);
properties.put("db.name",name);
properties.put("db.pwd",pwd);
//写入
try {
OutputStream outputStream = new FileOutputStream("test.properties");
//写文件--第二个参数为描述
properties.store(outputStream,"update value!");
//关闭流
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 清除配置文件
*/
public static void clear(){
Properties properties = new Properties();
InputStream inputStream = null;
try {
inputStream = new FileInputStream("test.properties");
properties.load(inputStream);
properties.clear();
OutputStream outputStream = new FileOutputStream("test.properties");
properties.store(outputStream,"");
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//测试
public static void main(String[] args) {
//写
// writeConfig("2.0","lsq666","666666");
//读
readConfig();
System.out.println(demo.version);
System.out.println(demo.name);
System.out.println(demo.pwd);
clear();
}
}