我是 servlet 新手。我在 servlet.then 中使用以下代码,然后部署到 Jboss 4.1 。 backup_database_configuration_location是属性文件的位置。但找不到。如何指定 war 文件中的目录? 提前感谢大家
try {
backupDatabaseConfiguration = new Properties();
FileInputStream backupDatabaseConfigurationfile = new FileInputStream(backup_database_configuration_location));
backupDatabaseConfiguration.load(backupDatabaseConfigurationfile);
backupDatabaseConfigurationfile.close();
} catch (Exception e) {
log.error("Exception while loading backup databse configuration ", e);
throw new ServletException(e);
}
最佳答案
如果将其放置在网络内容中,则使用ServletContext#getResourceAsStream()
:
InputStream input = getServletContext().getResourceAsStream("/WEB-INF/file.properties"));
getServletContext()
方法继承自 HttpServlet
。只需在 servlet 内按原样调用即可。
如果它被放置在类路径中,则使用ClassLoader#getResourceAsStream()
:
InputStream input = Thread.currentThread().getContextClassLoader().getResourceAsStream("file.properties");
与Class#getResourceAsStream()
的区别是你不依赖于加载该类的类加载器(这可能与线程正在使用的类加载器不同,如果该类实际上是打包在 JAR 中的实用程序类,并且特定的类加载器可能无权访问某些类路径)。
关于java - 如何指定 war 文件中的目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2288218/