簡體   English   中英

為什么我無法在類路徑中使用getResourceAsStream讀取屬性文件(在WEB-INF / lib下)

[英]Why I cant read properties file using getResourceAsStream when it is in classpath (under WEB-INF/lib)

當屬性文件位於類路徑(在WEB-INF \\ lib文件夾下)時,我正在測試使用getResourceAsStream讀取屬性文件。 由於某種原因,它不起作用。 有人可以告訴我我做錯了嗎?

這是我的環境:操作系統是Windows7。IDE是Eclipse 4.2.3 Kepler 64位。 服務器是在8081端口上運行的Tomcat 6.0.37。

我創建了一個Web應用程序MyWebProject

我有一個位於WEB-INF\\lib文件夾中的app.properties文件。 這是app.properties文件的內容:

數據源= JDBC / MYDB

我創建了一個AppProperties類,它讀取該文件。 這是課程:

public final class AppProperties {

    private static String DATA_SOURCE_NAME;

    public static String getDataSourceName() {
        return DATA_SOURCE_NAME;
    }

    static {

        ClassLoader classLoader = null;
        InputStream propertiesFile = null;
        Properties properties = null;
        final String PROPERTIES_FILE_NAME = "app.properties";

        properties = new Properties();
        classLoader = Thread.currentThread().getContextClassLoader();
        System.out.println("AppProperties: Name of classLoader = " + classLoader.getClass().getName());
        propertiesFile = classLoader.getResourceAsStream(PROPERTIES_FILE_NAME);
        System.out.println("AppProperties: propertiesFile = " + propertiesFile);

    }
}

然后,我創建了一個Servlet AppPropertiesServlet進行測試:

public class AppPropertiesServlet extends HttpServlet {

    public AppPropertiesServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {       
        String dataSourceName = null;

        dataSourceName = AppProperties.getDataSourceName();
    }
}

我在Tomcat上部署了Web應用程序MyWebProject 因此,在Tomcat的webapps文件夾下,使用所有必需的文件創建了一個新文件夾MyWebProject 然后,我運行servlet http://localhost:8081/MyWebProject/AppPropertiesServlet ,這就是Tomcat控制台上顯示的內容:

AppProperties:classLoader的名稱= org.apache.catalina.loader.WebappClassLoader
AppProperties:propertiesFile = null

為什么propertiesFile為null? app.properties文件在WEB-INF\\lib的文件夾MyWebProject文件夾,但不知何故類加載器是無法找到它。 奇怪。 我在這里做錯了什么?

謝謝

如果您希望它位於WEB-INF/lib則必須將其包裝在JAR中。

如果您希望它像普通文件一樣,則必須位於WEB-INF/classes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM