J2EE之ServletContext讀取資源檔

來源:互聯網
上載者:User

標籤:

ServletContext讀取資源檔內容的方式有兩種:

方法1.

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/data.properties");Properties pros = new Properties();pros.load(in);String username = pros.getProperty("username");String password = pros.getProperty("password");System.out.println("username = " + username);System.out.println("password = " + password);}


這裡須要注意的是data.properties檔案的位置在Myeclipse的src檔案夾下,為啥getResourceAsStream方法傳入的參數確實"/WEB-INF/classes/data.properties"

這是由於這些代碼有webserver運行,當項目公布以後。data.properties檔案就會被放到tomcat安裝檔案所在目錄下。

watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbTYzMTUyMTM4Mw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast" >

所以這裡傳入參數就解釋清楚了。

方法2

public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {String path = this.getServletContext().getRealPath("/WEB-INF/classes/data.properties");FileInputStream in = new FileInputStream(path);Properties pros = new Properties();pros.load(in);String username = pros.getProperty("username");String password = pros.getProperty("password");System.out.println("username = " + username);System.out.println("password = " + password);}

這裡首先通過getRealPath方法擷取data.properties檔案的絕對路徑,然後通過FileInputStream擷取檔案流。

J2EE之ServletContext讀取資源檔

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.