讀取web中的資源配置文件

一.軟件開發過程中常有的兩種配置文件是:

       1. .xml配置文件

        2. .properties配置文件

        當要用的數據間沒有關係是用到.properties文件。

二.在servlet中一般使用ServletContext讀取.properites配置文件。一般代碼格式爲:

      InputStream in=this.getServletContext().getResourceAsStream("對應web映射到服務器下得目錄");

      Properties prop=new Properties();

      rops.load(in);

      props.getProperty("");//對應properties文件中等號(“=”)左面的數據

三.如配置文件爲:

      url=jdbc:mysql://localhost:3306/test
      username=root
      password=root

     讀取方式:

       InputStream in=this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");//目錄爲服務器下對應的目錄,在本地磁盤映射到服務器下得目錄,               此      處是在本地src目錄下若再cn.itcast包下則爲/WEB-INF/classes/cn/itcast/db.properties,若在webroot下則直接爲/db.properties
        Properties props=new Properties();//map
        props.load(in);
        
        String url=props.getProperty("url");
        String username=props.getProperty("username");
        String password=props.getProperty("password");

注:

讀取資源文件需要注意的問題:下面代碼不可行,最好採用servletContext去讀
    private void test4() throws IOException {
        FileInputStream in =new FileInputStream("src/db.properties");//改成classes目錄也不行,採用相對路徑,相對類加載器的目錄(服務器啓動目錄)
        Properties props=new Properties();
        props.load(in);
     可以通過servletContext的getRealPath得到資源的絕對路徑後,再通過傳統流讀取資源文件,可以得到文件的名稱
    private void test5() throws IOException {
        String path=this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
        FileInputStream in=new FileInputStream(path);
        Properties props=new Properties();
        props.load(in);   

四.得到配置文件的文件名

        String path=this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");//得到真實路徑名
        String filename=path.substring(path.lastIndexOf("\\")+1);//注意加1
        System.out.println("當前讀取到得資源名稱是:"+filename);
        FileInputStream in=new FileInputStream(path);
        Properties props=new Properties();
        props.load(in);   

五.不是servlet的java程序讀取web配置文件

      雖然可以使用參數傳遞ServletContext,但不使用,外部侵入了數據庫層,不符合軟件設計思想。只能通過類裝載器去讀了,類裝載器不僅可以裝載類,也可以裝載配置文件。

         Properties dbconfig=new Properties();
        InputStream in=UserDao.class.getClassLoader().getResourceAsStream("db.properties");
        dbconfig.load(in);

      雖然可以讀取資源文件的數據,但是無法獲取更新後的數據。通過類裝載器的方式得到資源文件的位置,再通過傳統方式讀取資源文件的數據,這樣可以讀取到更新後的數據:

      String path=UserDao.class.getClassLoader().getResource("db.properties").getPath();
        
        FileInputStream in=new FileInputStream(path);
        Properties dbconfig=new Properties();
        dbconfig.load(in);

       注意:servletcontext讀取的配置文件不能太大


    

      


發佈了17 篇原創文章 · 獲贊 7 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章