How to get the root path of a web project in java EE

雨燕双飞 提交于 2019-12-11 14:23:19

问题


I'm using java EE for my dynamic web project. And i put sitemap.xml file in the root path. Now i need a path to that file to modify. I try:

String path = getClass().getClassLoader().getResource(".").getPath() +"\\sitemap.xml";

but The system cannot find the file specified. I'm using window, what do i need to change when i upload my project to linux hosting?


回答1:


The ClassLoader#getResource() only finds classpath resources, not web resources. The sitemap.xml is clearly a web resource. You should be using ServletContext#getResource() instead, or its JSF counterpart ExternalContext#getResource() — as indicated by your question history, you're using JSF.

URL url = externalContext.getResource("/sitemap.xml");

Or, for reading only:

InputStream input = externalContext.getResourceAsStream("/sitemap.xml");

Generally, you shouldn't be interested at all in the actual disk file system path being used. This is usually a temporary folder location or even an in-memory location.


Unrelated to the concrete question, writing to it is a whole story apart. Neither classpath resources nor web resources are intented to be writable from inside the Java EE application. Even if it were possible (i.e. it's not an in-memory resource), all changes would get completely lost whenever you redeploy the WAR or even when you just restart the server, for the very simple reason that those changes are not reflected in the original WAR file. Given the specific filename of "sitemap.xml", I have the impression that you intented a more permanent storage. In that case, I strongly recommend to look for a different solution. E.g. store the file in a fixed path outside the WAR, or just the data structure in a database.




回答2:


First of all, try not to use windows file separator "\", cause it's platform dependent. Instead, you can use "/" (as far as I remember, it should be replaced by JVM to suitable separator) or, even better, File.separator.



来源:https://stackoverflow.com/questions/20284112/how-to-get-the-root-path-of-a-web-project-in-java-ee

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