Properties类则是properties文件和程序的中间桥梁,不论是从properties文件读取信息还是写入信息到properties文件都要经由Properties类。该类主要用于读取Java的配置文件,不同的编程语言有自己所支持的配置文件,配置文件中很多变量是经常改变的,为了方便用户的配置,能让用户够脱离程序本身去修改相关的变量设置,所以产生了Properties类。就像在Java中,其配置文件常为.properties文件,是以键值对的形式进行参数配置的。
Properties类的主要方法
properties除了从 Hashtable 中所定义的方法,Properties 还定义了以下方法:
1.为properties对象添加属性和获取值
@Test
public void setAndGetProperty() {
Properties pro=new Properties();
//设置值
pro.setProperty("driver", "com.mysql.jdbc.Driver");
pro.setProperty("url", "jdbc:mysql///user");
pro.setProperty("user", "root");
pro.setProperty("password", "451535");
//获取值:
//1、getProperty(String key)方法 通过键获取值
String str= pro.getProperty("driver");
System.out.println(str);
//2、getProperty(String key, String defaultValue)重载方法
//当properties对象中没有所指定的键值时,显示给定的默认值
String str2=pro.getProperty("driver", "没有该值");
String str3=pro.getProperty("Tsinghua", "没有该值");
System.out.println(str2);
System.out.println(str3);
}
运行结果:
2.getProperties方法
public static void main(String[] args) {
Properties properties = System.getProperties();
properties.list(System.out);
}
3.以properties配置文件格式写入到硬盘中的某个文件夹
@Test
public void storePropertiesToHardFile() throws FileNotFoundException, IOException{
Properties pro=new Properties();
pro.setProperty("driver", "com.mysql.jdbc.Driver");
pro.setProperty("url", "jdbc:mysql///user");
pro.setProperty("user", "root");
pro.setProperty("password", "451535");
//1.通过字节流的形式
//store(OutputStream out, String comments)
//outputStream:字节输出流 comments:配置文件说明
pro.store(new FileOutputStream(new File("d:/others/jdbc.properties")), "数据库配置文件");
//2.通过字符流的形式
//store(Writer writer, String comments)
//writer:字符输出流 comments:配置文件说明
pro.store(new FileWriter("d:/others/jdbc.properties"), "数据库配置文件");
}
运行结果:
4.以XML配置文件格式写入到硬盘中的某个文件夹
@Test
public void storeXMLToHardFile() throws FileNotFoundException, IOException{
Properties pro=new Properties();
pro.setProperty("driver", "com.mysql.jdbc.Driver");
pro.setProperty("url", "jdbc:mysql///user");
pro.setProperty("user", "root");
pro.setProperty("password", "451535");
//1.不指定编码 默认为:UTF-8
//storeToXML(OutputStream os, String comment)
//因为XML不是文本文件,所以只能用字节流,为不能用字符流
pro.storeToXML(new FileOutputStream("d:/test/jdbc.xml"), "数据库配置文件");
//1.不指定编码
//storeToXML(OutputStream os, String comment)
//因为XML不是文本文件,所以只能用字节流,为不能用字符流
pro.storeToXML(new FileOutputStream("d:/test/jdbc2.xml"), "数据库配置文件", "GBK");
}
5.以properties和XML配置文件格式写入到应用程序的某个文件夹(本例写入应用程序的classPath类路径下)
@Test
public void storeToClassPsth() throws FileNotFoundException, IOException{
Properties pro=new Properties();
pro.setProperty("driver", "com.mysql.jdbc.Driver");
pro.setProperty("url", "jdbc:mysql///user");
pro.setProperty("user", "root");
pro.setProperty("password", "451535");
pro.store(new FileOutputStream("src/jdbc.properties"), "数据库配置文件");
pro.storeToXML(new FileOutputStream("src/jdbc.xml") , "数据库配置文件");
}
运行结果: