Relative File Path Problem

☆樱花仙子☆ 提交于 2019-12-24 02:25:31

问题


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.



来源:https://stackoverflow.com/questions/3224072/relative-file-path-problem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!