如何从 WEB-INF 文件夹外部的文件夹中读取文件



我有一个Java的Web应用程序项目。如果我部署该项目,则该项目在文件夹级别的 Tomcat 服务器上具有如下结构:

-conf
-图像
-元信息
信息-配置 文件
-网络信息

我想从"配置文件"和"配置"文件夹中读取一些文件。我试过使用

Properties prop = new Properties();
try{
    prop.load(new FileInputStream("../webapps/WebApplicatioProject/profiles/file_001.properties"));
} catch (Exception e){
   logger.error(e.getClass().getName());
}

它没有用。然后我尝试了

Properties prop = new Properties();
try{
    prop.load(getClass().getResourceAsStream("../../../../profiles/fille_001.properties"));
} catch (Exception e){
    logger.error(e.getClass().getName());
}

它也不起作用。

如何从 WEB-INF 文件夹之外的文件夹"配置文件"和"conf"读取文件?

如果文件位于WebContext文件夹下,我们通过调用ServletContext对象引用得到。

Properties props=new Properties();
    props.load(this.getServletContext().getResourceAsStream("/mesdata/"+fileName+".properties"));

如果文件位于类路径下,则使用类加载器我们可以获取文件位置

Properties props=new Properties();
    props.load(this.getClass().getClassLoader.getResourceAsStream("/com/raj/pkg/"+fileName+".properties"));

正如 Stefan 所说,不要把它们放在 WEB-INF/...所以把它们放到 WEB-INF/中,然后以这种方式阅读它们:

ResourceBundle resources = ResourceBundle.getBundle("fille_001");

现在,您可以访问 fille_001.properties 中的属性。

您可以使用

ServletContext.getResource(或getResourceAsStream)通过相对于 Web 应用程序的路径(包括但不限于 WEB-INF 下的路径)访问资源。

InputStream in = ctx.getResourceAsStream("/profiles/fille_001.properties");
if(in != null) {
  try {
    prop.load(in);
  } finally {
    in.close();
  }
}

如果真的必须,可以对该位置进行逆向工程。在捕获通用异常和日志 File.getPath() 之前捕获 FileNotFoundException,这会输出绝对文件名,您应该能够看到相对路径来自哪个目录。

你应该使用ServletContext.getResource . getResourceAsStream本地为我工作,但在 Jenkins 中失败了。

您可以使用

this.getClass().getClassLoader().getResourceAsStream("../../profiles/fille_001.properties")

基本上,类加载器开始在文件夹中查找资源Web-Inf/classes。因此,通过提供相对路径,我们可以访问文件夹之外web-inf位置。

最新更新