簡單讀取dataSource.properties配置文件

package common.newEntity;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.springframework.core.io.ClassPathResource;
/**
 * ********************************************************
 * @ClassName: newEntity
 * @Description: 
 * @author DoDo
 * @date 2017-12-27 下午06:29:37
 *******************************************************
 */
public class newEntity {
     //讀取配置文件
     public static void main(String[] args) throws Exception { 
            //讀取方式一
            // ClassPathResource的作用,如果沒有指定相對的類名,該類將從類的根路徑開始尋找某個 resource,如果指定了相對的類名,則根據指定類的相對路徑來查找某個resource
            // ClassPathResource cr = new ClassPathResource("com.md.util/dataSource.properties");//會重新加載spring框架
            ClassPathResource cr = new ClassPathResource("dataSource.properties");
            // properties是配置文件,主要的作用是通過修改配置文件可以方便的修改代碼中的參數,實現不用改class文件即可靈活變更參數。(方便使用)
            Properties pros = new Properties();
            try {
                //Properties的load方法其實就是傳進去一個輸入流,字節流或者字符流,字節流利用InputStreamReader轉化爲字符流,
                //然後字符流用BufferedReader包裝,BufferedReader讀取properties配置文件
                pros.load(cr.getInputStream());
                System.out.println(pros.getProperty("driver")); 
            } catch (IOException ex) {
                System.out.println("數據庫連接文件不存在");
            }
            //讀取方式二
            Properties properties=new Properties();  
            properties.load(new FileInputStream("E:/dataSource.properties"));  
            System.out.println(properties.getProperty("driver"));  
        }  
}

輸出:
com.mysql.jdbc.Driver
com.mysql.jdbc.Driver

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章