Relative File Path Problem

2019-07-10 07:46发布

问题:

I am developing a portlet that is trying to read in a config file. I am developing it in an eclipse project. I currently have the config file placed inside my WEB-INF folder (which is in root/WEB-INF/), and its called config.properties. How can I access this file using relative path in my java source code? (which is in root/src/package/mysource.java)

For example,

File myfile = new File("WHAT DO I PUT HERE/config.properties");

Any help you can provide would be great!

回答1:

Since this is a portlet, you'll probably want to use the PortletContext.

Although there is a getRealPath method, I would avoid it as it is dependent on how the portal application is deployed - there is no guarantee that the resource is going to map to a file on the file system. Go instead for getResourceAsStream (or, if you must, getResource).



回答2:

I would load that using the servlet context and its getResourceAsStream() method instead of a File. Like this....

Sorry, you said portlet. You'll need javax.portlet.PortletContext then.

You can get the PortletContext from the PortletSession. You can create a PortletSession from a PortletRequest.



标签: java portlet zk