Reputation: 29
I have a Web Application project in java. If I deploy that project, then the project has on the Tomcat server at folder level a structure as follows:
-conf
-image
-META-INF
-profiles
-WEB-INF
I want to read some files from the folder "profiles" and "config". I tried using
Properties prop = new Properties();
try{
prop.load(new FileInputStream("../webapps/WebApplicatioProject/profiles/file_001.properties"));
} catch (Exception e){
logger.error(e.getClass().getName());
}
it did not work. Then I tried with
Properties prop = new Properties();
try{
prop.load(getClass().getResourceAsStream("../../../../profiles/fille_001.properties"));
} catch (Exception e){
logger.error(e.getClass().getName());
}
it did not work also.
How can you read files from folder "profiles" and "conf", which are outside the WEB-INF folder?
Upvotes: 1
Views: 4726
Reputation: 454
if the file is under WebContext folder we get by calling ServletContext object reference.
Properties props=new Properties();
props.load(this.getServletContext().getResourceAsStream("/mesdata/"+fileName+".properties"));
if the file is under class path by using class loaders we can get the file location
Properties props=new Properties();
props.load(this.getClass().getClassLoader.getResourceAsStream("/com/raj/pkg/"+fileName+".properties"));
Upvotes: 2
Reputation: 1
You can use
this.getClass().getClassLoader().getResourceAsStream("../../profiles/fille_001.properties")
Basically Classloader starts to look resources into Web-Inf/classes
folder. So by giving relative path we can access location outside of web-inf
folder.
Upvotes: -1
Reputation: 101
You should use ServletContext.getResource
. getResourceAsStream
works locally for me but fails in Jenkins.
Upvotes: 0
Reputation: 122424
You can use ServletContext.getResource
(or getResourceAsStream
) to access resources using paths relative to the web application (including but not limited to those under WEB-INF
).
InputStream in = ctx.getResourceAsStream("/profiles/fille_001.properties");
if(in != null) {
try {
prop.load(in);
} finally {
in.close();
}
}
Upvotes: 1
Reputation: 3774
As Stefan said, don't put them out WEB-INF/... so put them into WEB-INF/ and then read them in this way:
ResourceBundle resources = ResourceBundle.getBundle("fille_001");
Now you can access the properties inside fille_001.properties.
Upvotes: 1
Reputation: 1000
If you really must, you can reverse engineer the location. Catch a FileNotFoundException before you catch the generic Exception and log File.getPath(), this puts out the absolute filename, you should be able to see form which directory the relative paths are derived from.
Upvotes: 0