类 Properties 使用 转
- DataBase.properties的内容
- driver=com.mysql.jdbc.Driver
- url=jdbc:mysql://127.0.0.1:3306/jpetstore
- username=root
- password=dongguoh
- DataBase.xml的内容
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
- <properties>
- <comment>PropertiesTest</comment>
- <entry key="driver">com.mysql.jdbc.Driver</entry>
- <entry key="url">jdbc:mysql://127.0.0.1:3306/jpetstore</entry>
- <entry key="username">root</entry>
- <entry key="password">dongguoh</entry>
- </properties>
- 下面是测试类
- package DataBase;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.util.Iterator;
- import java.util.Properties;
- import java.util.Set;
- public class TestProperties {
- public static void main(String[] args) {
- TestProperties test=new TestProperties();
- test.luanch();
- test.luanchXML();
- }
- private void luanch(){
- Properties ppt=new Properties();
- try {
- String path=this.getClass().getResource("/").getPath();
- path=path+"DataBase/DataBase.properties";
- FileInputStream fis=new FileInputStream(path);
- ppt.load(fis);
- fis.close();
- Set set=ppt.keySet();
- Iterator it=set.iterator();
- System.out.println("*********显示的读取DataBase.properties显示的内容*****");
- while(it.hasNext()){
- String id=(String)it.next();
- System.out.println(id+"="+ppt.getProperty(id));
- }
- System.out.println("另外一种显示方式");
- ppt.list(System.out);
- } catch (FileNotFoundException e) {
- System.out.println("找不到DataBase.properties这个文件,或者是路径发生错误");
- } catch (IOException e) {
- System.out.println("加载DataBase.properties文件时出错!!");
- }
- }
- private void luanchXML(){
- Properties ppt=new Properties();
- try {
- String path=this.getClass().getResource("/").getPath();
- path=path+"DataBase/DataBase.xml";
- System.out.println(path);
- FileInputStream fis=new FileInputStream(path);
- ppt.loadFromXML(fis);
- fis.close();
- Set set=ppt.keySet();
- Iterator it=set.iterator();
- System.out.println("*********显示的读取DataBase.xml 显示的内容*****");
- while(it.hasNext()){
- String id=(String)it.next();
- System.out.println(id+"="+ppt.getProperty(id));
- }
- } catch (FileNotFoundException e) {
- System.out.println("找不到DataBase.xml 这个文件,或者是路径发生错误");
- } catch (IOException e) {
- System.out.println("加载DataBase.xml 文件时出错!!");
- }
- }
- }
- 结果:
- *********显示的读取DataBase.properties显示的内容*****
- password=dongguoh
- url=jdbc:mysql://127.0.0.1:3306/jpetstore
- driver=com.mysql.jdbc.Driver
- username=root
- 另外一种显示方式
- -- listing properties --
- url=jdbc:mysql://127.0.0.1:3306/jpetstore
- password=dongguoh
- driver=com.mysql.jdbc.Driver
- username=root
- /E:/MyJavaProject/Ibatis/WebRoot/WEB-INF/classes/DataBase/DataBase.xml
- *********显示的读取DataBase.xml 显示的内容*****
- password=dongguoh
- url=jdbc:mysql://127.0.0.1:3306/jpetstore
- driver=com.mysql.jdbc.Driver
- username=root