通過ServletContext獲得工程根目錄路徑、讀取文件以及獲得classpath目錄下的文件


HttpServletDemo02.java:

package com.fl.servlet;


import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



public class HttpServletDemo02 extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
    }
    @Override
    public void init(ServletConfig config) throws ServletException {
        ServletContext sc = config.getServletContext();
        //不管根目錄下是否有temp.txt,在這里不會檢測。
        String path = sc.getRealPath("temp.txt");
        //不管根目錄下有沒有upload目錄,這里也不會報錯,而是會
        //直接輸出根目錄的完整目錄后,再在后面加上upload。
        String path1 = sc.getRealPath("/upload");
        //因此一般getRealPath用於獲取根目錄路徑。
        String path2 = sc.getRealPath("/");
        System.out.println(path);
        System.out.println(path1);
        System.out.println(path2);
        //這里通過完整路徑,把文件放入流中。
        InputStream in = sc.getResourceAsStream("/WEB-INF/temp.txt");
        Properties prop = new Properties();
        
        try {
            prop.load(in);
            System.out.println(prop.get("key"));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <servlet-name>HttpServletDemo02</servlet-name>
    <servlet-class>com.fl.servlet.HttpServletDemo02</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>HttpServletDemo02</servlet-name>
    <url-pattern>/servlet/HttpServletDemo02</url-pattern>
  </servlet-mapping>
</web-app>

temp.txt:

    key=dddd;

 

輸出結果:

 

獲得classpath目錄下的文件:

 

下面有兩種方法:

InputStream in = sc.getResourceAsStream("/WEB-INF/classes/temp.txt");//這種方式不太好
InputStream in = this.getClass().getClassLoader().getResourceAsStream("temp.txt");//類加載方式,不依賴ServletCntext,任何類都可以獲得classpath下的文件。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM