Properties类是一个属性集,它的主要作用就是读写资源配置文件,该类中的键与值都要求是字符串
资源配置文件的好处就是可以动态的切换不同数据库,你只需要更改字符串即可,不需要更改源码,然后再进行编译
下面是它的几个常用方法
1.存储与读取
import java.util.Properties;
/* *存储:setProperties(String key,String value) *读取:getProperty(String key,String defaultValue) *读取的时候,如果有key,则返回setProperties中设置的value,否则返回defaultValue */
public class Test {
public static void main(String[] args) {
//创建一个Properties对象
Properties p=new Properties();
//存储,key和value对应
p.setProperty("driver", "oracle.jdbc.driver.OracleDriver");
//读取
String url=p.getProperty("pwd", "test");
System.out.println(url);
}
}
此时输出 oracle.jdbc.driver.OracleDriver ,如果把set语句注释掉,则输出test
2.输出到文件中
这里有两种文件格式 * .properties 和 * . xml,分别对应不同的方法,需要注意的是后缀名只是打开文件的所用工具不同,并不会改变文件的内容,要输出就需要用到IO流,
(* .properties
store(OutputStream out,String comments)
store(Writer writer,String comments)
(* . xml
storeToXML(OutputStream os,String comment)
storeToXML(OutputStream os,String comment,String encoding)
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties p=new Properties();
p.setProperty("driver", "oracle.jdbc.driver.OracleDriver");
p.setProperty("user", "scott");
p.setProperty("pwd", "tiger");
//这里的路径是绝对路径,如果使用相对路径,则保存到当前工程文件夹下
p.store(new FileOutputStream(new File("d:/db.properties")),"db配置");
p.storeToXML(new FileOutputStream(new File("d:/db.xml")), "db配置");
}
}
运行以后,打开D盘就会有出现db.properties和db.xml文件,用记事本打开是这样的
TIPS:相对路径和绝对路径
windows下的绝对路径 ,就是带盘符 比如 d:/ ; 相对路径就是相对我们当前的项目
3.从文件中读取
前提是 d:/db.properties文件存在,且存储了相关属性,才可以正确输出
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
/* *load(InputStream inStream) *load(Reader reader) */
public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties p=new Properties();
//p.load(new FileInputStream("d:/db.properties"));
p.load(new FileReader("d:/db.properties"));
String url=p.getProperty("driver");
System.out.println(url);
}
}
输出结果为:oracle.jdbc.driver.OracleDriver
4.使用类相对路径读取配置文件
代码中的db.properties是保存在项目中的,
路径为D:\Myeclipse\Workspace\imooc_collection\src\com\bjsxt\db.properties
用以下两种方法来代替输出流,第一种“/”代表了bin目录,而第二种“”代表bin目录
Test.class.getResourceAsStream(“/com/wwy/db.properties”)
Thread.currentThread().getContextClassLoader().getResourceAsStream(“com/wwy/db.properties”)
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
public class Test {
public static void main(String[] args) throws FileNotFoundException, IOException {
Properties p=new Properties();
//p.load(Test.class.getResourceAsStream("/com/wwy/db.properties"));
p.load(Thread.currentThread().getContextClassLoader().getResourceAsStream
("com/wwy/db.properties"));
System.out.println(p.getProperty("driver"));
}
}
输出结果为 :oracle.jdbc.driver.OracleDriver