Properties 继承于 Hashtable。表示一个持久的属性集.属性列表中每个键及其对应值都是一个字符串 Properties集合是一个唯一和IO流相结合的集合 表示一个持久的属性集。它使用键值结构存储数据,每个键及其对应值都是一个字符串。该类也被许多Java类使用,比如获取系统属性时,System.getProperties 方法就是返回一个Properties对象 Properties(Java.util.Properties),该类主要用于读取Java的配置文件,不同的编程语言有自己所支持的配置文件,配置文件中很多变量是经常改变的,为了方便用户的配置,能让用户够脱离程序本身去修改相关的变量设置。就像在Java中,其配置文件常为.properties文件,是以键值对的形式进行参数配置的 java.util.Properties集合 extends Hashtable
implements Map Hashtable集合不被常用,但是Properties集合却很常用
一、properties文件
Properties文件是java中很常用的一种配置文件,文件后缀为“.properties”,属文本文件,文件的内容格式是“键=值”的格式,可以用“#”作为注释,java编程中用到的地方很多,运用配置文件,可以便于java深层次的解耦。例如java应用通过JDBC连接数据库时,通常需要在代码中写数据库连接字符串,下面贴出java通过JDBC连接数据库的代码(以mysql为例):
//mysql提供的Driver接口的实现类String driver="com.mysql.jdbc.Driver";//此处为"jdbc:mysql://localhost:3306/user"的简化形式,user为数据库名String jdbcUrl="jdbc:mysql:///user";String user="root";String password="451535";//1.注册驱动(通过反射动态实例化mysql数据库驱动类)//复制mysql-connector-java-5.1.37-bin.jar到项目的libs目录下 右键-->Add As LibraryClass.forName(driver);Connection conn= DriverManager.getConnection(jdbcUrl,user,password);Statement stmt = conn.createStatement(); //2.获取执行sql的对象 StatementString sql = "update user_table set money = 500 where id = 1"; //3.定义sql语句int count = stmt.executeUpdate(sql); //4.执行sqlSystem.out.println(count); //5.处理结果stmt.close(); //6.释放资源conn.close();
以上代码连接mysql数据库没有任何问题,但是我想换成Oracle数据库,问题就来了,不是不能改,而是我必须得到java源代码中修改代码,这样的硬代码耦合在java中一般不这么做(菜鸟程序员有可能)。所以,为了达到解耦的目的,我们可以用配置文件来储存数据库的连接字符串。下面贴一份保存数据库连接字符串的properties配置文件 jdbc.properties:
driver=com.mysql.jdbc.DriverjdbcUrl=jdbc:mysql://localhost:3306/useruser=rootpassword=451535
这样我们就可以通过加载properties配置文件来连接数据库,达到深层次的解耦目的,如果想要换成oracle或是DB2,我们只需要修改配置文件即可,不用修改任何代码就可以更换数据库。
二、Properties类
| 序号 | 方法描述 |
|---|---|
| Object setProperty(String key, String value) | 调用 Hashtable 的方法 put |
| String getProperty(String key) | 用指定的键在此属性列表中搜索属性 |
| String getProperty(String key, String defaultProperty) | 用指定的键在属性列表中搜索属性 此方法相当于Map集合中的get(key)方法 |
| Set |
所有键的名称的集合,其中该键及其对应值是字符串 此方法相当于Map集合中的keySet方法 |
| void load(InputStream streamIn) throws IOException | 从输入流中读取属性列表(键和元素对) |
| load(Reader reader) | 按简单的面向行的格式从输入字符流中读取属性列表(键和元素对 |
| loadFromXML(InputStream in) | 将指定输入流中由 XML 文档所表示的所有属性加载到此属性表中 |
| void list(PrintStream streamOut) | 将属性列表输出到指定的输出流 |
| void list(PrintWriter streamOut) | 将属性列表输出到指定的输出流 |
| Enumeration propertyNames( ) | 按简单的面向行的格式从输入字符流中读取属性列表(键和元素对) |
| void store(OutputStream streamOut, String description) | 以适合使用 load(InputStream)方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。 |
| void **store(Writer writer, String comments) ** | 以适合使用 load(Reader) 方法的格式,将此 Properties 表中的属性列表(键和元素对)写入输出字符 |
| storeToXML(OutputStream os, String comment) | 发出一个表示此表中包含的所有属性的 XML 文档 |
| storeToXML(OutputStream os, String comment, String encoding) | 使用指定的编码发出一个表示此表中包含的所有属性的 XML 文档 |
1.为properties对象添加属性和获取值
import java.util.*;public class PropertiesDemo {public static void main(String[] args) {setAndGetProperty();}// @Testpublic static void setAndGetProperty() {final Properties pro = new Properties();// 设置值pro.setProperty("driver", "com.mysql.jdbc.Driver");pro.setProperty("url", "jdbc:mysql///user");pro.setProperty("user", "root");pro.setProperty("password", "123456");// 1、getProperty(String key)方法 通过键获取值final String str = pro.getProperty("driver");System.out.println(str);// 2、getProperty(String key, String defaultValue)重载方法// 当properties对象中没有所指定的键值时,显示给定的默认值final String str2 = pro.getProperty("driver", "没有该值");final String str3 = pro.getProperty("haha", "没有该值");System.out.println(str2);System.out.println(str3);}}/*com.mysql.jdbc.Drivercom.mysql.jdbc.Driver没有该值*/
import java.util.*;
public class PropDemo {
public static void main(String args[]) {
Properties capitals = new Properties();
Set states;
String str;
capitals.put("Illinois", "Springfield");
capitals.put("Missouri", "Jefferson City");
capitals.put("Washington", "Olympia");
capitals.put("California", "Sacramento");
capitals.put("Indiana", "Indianapolis");
// Show all states and capitals in hashtable.
states = capitals.keySet(); // get set-view of keys
Iterator itr = states.iterator();
while (itr.hasNext()) {
str = (String) itr.next();
System.out.println("The capital of " + str + " is " + capitals.getProperty(str) + ".");
}
// look for state not in list -- specify default
str = capitals.getProperty("Florida", "Not Found");
System.out.println("The capital of Florida is " + str + ".");
}
}
/*
The capital of Missouri is Jefferson City.
The capital of Illinois is Springfield.
The capital of Indiana is Indianapolis.
The capital of California is Sacramento.
The capital of Washington is Olympia.
The capital of Florida is Not Found.
*/
2.以properties配置文件格式写入到硬盘中的某个文件夹(本例写入到当前运行文件夹中):
import java.io.*;
import java.util.*;
public class PropertiesDemo {
public static void main(String[] args) throws FileNotFoundException, IOException {
storePropertiesToHardFile();
}
public static 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", "123456");
// 1.通过字节流的形式
// store(OutputStream out, String comments)
// outputStream:字节输出流 comments:配置文件说明
pro.store(new FileOutputStream(new File("./jdbc.properties")), "数据库配置文件");
// 2.通过字符流的形式
// store(Writer writer, String comments)
// writer:字符输出流 comments:配置文件说明
pro.store(new FileWriter("./jdbc.properties"), "数据库配置文件");
}
}

3.以XML配置文件格式写入到硬盘中的某个文件夹(本例写入到当前运行文件夹中):
import java.io.*;
import java.util.*;
public class PropertiesDemo {
public static void main(String[] args) throws FileNotFoundException, IOException {
storeXMLToHardFile();
}
// @Test
public static 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("./jdbc.xml"), "数据库配置文件");
// 1.不指定编码
// storeToXML(OutputStream os, String comment)
// 因为XML不是文本文件,所以只能用字节流,为不能用字符流
pro.storeToXML(new FileOutputStream("./jdbc2.xml"), "数据库配置文件", "GBK");
}
}


4.以properties和XML配置文件格式写入到应用程序的某个文件夹(本例写入应用程序的classPath类路径下):
import java.io.*;
import java.util.*;
public class PropertiesDemo {
public static void main(String[] args) throws FileNotFoundException, IOException {
storeToClassPsth();
}
// @Test
public static 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", "123456");
pro.store(new FileOutputStream("src/jdbc.properties"), "数据库配置文件");
pro.storeToXML(new FileOutputStream("src/jdbc.xml"), "数据库配置文件");
}
}
5.加载和读取配置文件(以properties文件为例)
import java.io.*;
import java.util.*;
public class PropertiesDemo {
public static void main(String[] args) throws FileNotFoundException, IOException {
new PropertiesDemo().loadAndReadFile();
}
// @Test
public void loadAndReadFile() throws FileNotFoundException, IOException {
Properties pro = new Properties();
// 通过字节输入流
// load(InputStream inStream)
pro.load(new FileInputStream("src/sql.properties"));
// 通过[类加载器]获取当前类路径(/bin路径)
pro.load(this.getClass().getResourceAsStream("/sql.properties"));
pro.load(this.getClass().getClassLoader().getResourceAsStream("sql.properties"));
// 也可以使用当前上下文的类加载器,不用“/”
pro.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("sql.properties"));
// 通过字符输入流
// load(Reader reader)
pro.load(new FileReader("src/jdbc.properties"));
System.out.println(pro.get("driver"));
// 以上几种加载配置文件的方法都可以使用,此处都列举出来。
}
}
/*
运行结果:
com.mysql.jdbc.Driver
*/
6.附上通过读取配置文件JDBC连接数据库的代码干货
public Connection getConnection() throws Exception{
Properties info=new Properties();
info.load(this.getClass().getClassLoader().getResourceAsStream("jdbc.properties"));
String driver=info.getProperty("driver");
String jdbcUrl=info.getProperty("jdbcUrl");
String user=info.getProperty("user");
String password=info.getProperty("password");
Class.forName(driver);
Connection connection=DriverManager.getConnection(jdbcUrl,user,password);
return connection;
}
与流相关的方法
store

load

总结
通过读取配置文件的形式可以实现代码的深层次解耦,在java编程中,配置文件的重要性更是不言而喻。java编程有一条不成文的规定就是:“约定大于配置,配置大于代码”意思就是能用约定的就不去配置,能用配置文件搞定的就不去写代码,真正牛逼的攻城狮(工程师)不是写代码,而是写配置。java的一些开源框架,如:Struts、Struts2、Hibernate、Spring、MyBatis等都大量的使用配置文件,我们在学习和工作中,都应该将“约定大于配置,配置大于代码”的思想运用到项目中,实现代码的解耦,体现出你比别人的高明之处,才能比别人优秀。
