2012-12-10 45 views
1

我在java中有一个Web应用程序项目。如果我部署项目,那么项目有Tomcat服务器上的文件夹层次的结构如下:如何从文件夹中读取WEB-INF文件夹外部的文件?

-conf
-image
-META-INF
-profiles
-WEB-INF

我想从文件夹“profiles”和“config”中读取一些文件。我试过使用

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文件夹以外的文件夹“profiles”和“conf”中读取文件?

+2

不要把服务器文件的WEB-INF之外,因为用户可以简单地输入WEBCONTEXT/conf目录在浏览器中读取文件。 – Stefan

回答

0

如果您确实需要,您可以对该位置进行逆向工程。在捕获通用异常并记录File.getPath()之前捕获FileNotFoundException,这将输出绝对文件名,您应该能够看到相对路径从哪个目录派生而来。

1

正如斯特凡说,不要把他们赶出WEB-INF/...所以把它们放到WEB-INF /,然后以这种方式阅读:

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

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

1

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

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

您应该使用ServletContext.getResourcegetResourceAsStream在本地为我工作,但在詹金斯失败。

-1

您可以使用

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

基本上类加载器开始寻找资源转化为Web-Inf/classes文件夹中。所以通过提供相对路径我们可以访问web-inf文件夹之外的位置。

+0

此解决方案不起作用。 –

1

如果该文件位于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")); 
相关问题