1. 程式人生 > >JavaWeb讀取專案配置檔案的方式

JavaWeb讀取專案配置檔案的方式

  • 配置檔案放在src的目錄下面:


     

     這是我們需要讀取的就是jdbc2.properties配置檔案資訊

  • @WebServlet("/servletProperties4")
    public class ServletProperties4 extends HttpServlet {
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            System.out.println("servletproeprties4執行了");
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("jdbc2.properties");
            Properties prop = new Properties();
            prop.load(inputStream);
            prop.list(System.out);
            //關閉流
            inputStream.close();
    
    
        }

    這時候就可以讀取到配置配置檔案裡面的資訊了!

     如果不用類載入器需要獲取配置檔案的需要在配置檔案前面加"/"

//InputStream resource = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
InputStream resource = JDBCUtils.class.getResourceAsStream("/druid.properties");
            pro.load(resource);

不用類載入器的時候讀取配置檔案需要在getResourceAsStream("/配置檔名字.properties")