Java: Universally accessing resource files regardless of application server

守給你的承諾、 提交于 2019-12-12 03:22:56

问题


I'm looking for the 'best practice' way to access resource files (for example a bunch of .xml files) as well as the folder structure in which they reside, regardless of the application server used.

Right now I'm using Wildfly 8 server and I access all src/main/resources/xxxx by getting the application real path then using Paths.get(resourcePath) as well as Files.walk(Paths.get(folderPath)) if I want to access a folder's files.

However, I faced a problem when I tried to deploy to Weblogic 12c, because this app server actually takes everything under WEB-INF/classes and creates a .jar file and adds it to WEB-INF/lib. I can still access singular resources using classLoader.getResource(resourcePath) but for some reason when I try to create a new File(Paths.get(resourcePath) or use Files.walk(Paths.get(folderPath)) it doesn't seem to be working. It throws an exception saying to file doesn't exist which I'm guessing is because it is not accessible since it is packaged inside a jar file.

I could potentially use classLoader.getResource(resourcePath) to access all my resources but unfortunately in my case I cannot know what resources will be available at compile time. I specifically NEED to be able to go through a selected folder's files and subfolders but I haven't found a common way to do it on both app servers, or ALL app servers for that matter.

Bonus points if the solution uses the new File api instead of creating a bunch of FileReaders but I'm ok with that too.


回答1:


You could place the XML files in a folder /WEB-INF/xml and then use the ServletContext to obtain a File or Path for that location.

Variant 1:

call servletContext.getResourceUrl("/WEB-INF/xml") to obtain a URL and convert this URL to a File or Path. But depending on the server this might return a non-file resource URL, e.g. a jndi:/ url.

Variant 2:

call servletContext.getRealPath("/WEB-INF/xml") to obtain a file string and convert this URL to a File or Path.



来源:https://stackoverflow.com/questions/33808119/java-universally-accessing-resource-files-regardless-of-application-server

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