Reputation: 456
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?
Upvotes: 0
Views: 2994
Reputation: 1108722
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.
Upvotes: 3
Reputation: 3486
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.
Upvotes: 1