关于Properties类的使用
java.util.Properties ,是java获取配置信息的类
Properties类的关系图
实现了Hashtable,使用map来保存配置信息,key值不能重复
构造方法
public Properties() {
this(null);
}
/**
* Creates an empty property list with the specified defaults.
*
* @param defaults the defaults.
*/
public Properties(Properties defaults) {
this.defaults = defaults;
}
使用方法
1.一般我们可以获取java程序配置的jvm参数
方式1
Properties properties=System.getProperties();
properties.list(System.out);
//单个
properties.getProperty("cwNacosUserName");
方式2 获取某个jvm参数
String jvmNacosUerName = System.getProperty("cwNacosUserName");
2 获取配置文件中的配置getClassLoader 加载
public class GetVersion {
private static final Properties gitProperties;
static {
Properties prop = new Properties();
try {
ClassLoader classLoader = GetVersion.class.getClassLoader();
InputStream in = classLoader.getResourceAsStream("gi t.comm.properties");
prop.load(in);
} catch (IOException e) {
e.printStackTrace();
}
gitProperties = prop;
}
public static void main(String[] args) {
System.out.println("commit id : " + gitProperties.getProperty("git.commit.id.abbrev"));
System.out.println("commit time : " + gitProperties.getProperty("git.commit.time"));
}
3.写入到Properties 文件
@Test
public void writeTest(){
try{
Properties properties=new Properties();
//用绝对路径
InputStream input=new BufferedInputStream(new FileInputStream("D:\\workspace\\JavaLearn\\src\\jdbc.properties"));
properties.load(new InputStreamReader(input,"utf-8"));
//多添加值。
properties.setProperty("id","1111");
OutputStream output=new FileOutputStream("D:\\jdbc.properties");
OutputStreamWriter out=new OutputStreamWriter(output,"utf-8");
properties.store(out,"填充数据");
}catch(Exception e){
e.printStackTrace();
}
}