简体   繁体   English

如何从Java获取src / main / resources路径

[英]How to get src/main/resources path from Java

I have some stuff under src/main/resources path. 我在src/main/resources路径下有一些东西。 Specifically I have a folder with report templates called reports. 具体来说,我有一个包含报告模板的文件夹,称为“报告”。

I understand that when the application is deployed/run all files and folders under src/main/resources go to the classpath, namely my project's WEB-INF/classes . 我了解到,在部署/运行应用程序时, src/main/resources下的所有文件和文件夹都将转到类路径,即项目的WEB-INF/classes

This means that a folder WEB-INF/classes/reports will be created in my server. 这意味着将在我的服务器中创建一个文件夹WEB-INF/classes/reports

Now I want to access my reports as paths , not as inputstream, because my reporting code in java supports a filepath and not an inputstream. 现在我要访问我的报告,路径 ,而不是为InputStream的,因为在Java我报告代码支持文件路径,而不是一个InputStream。 So I have to be able to get the WEB-INF/classes/reports absolute path (or relative, I don't care as long as it is right). 因此,我必须能够获取WEB-INF/classes/reports绝对路径(或相对路径,只要它是对的,我不在乎)。

Reading some answers regarding similar questions, I have already tried the following things: 阅读有关类似问题的一些答案,我已经尝试了以下操作:

  1. getClass().getResource(".").getPath(); --> this returns the exact path of the class I am currently at in my classpath, namely: C:\\Tools\\JBoss Application Server 7.1.1\\standalone\\deployments\\myProject.war\\WEB-INF\\classes\\aaa\\bbb\\ccc\\ddd ->这将返回我当前在类路径中的类的确切路径,即: C:\\Tools\\JBoss Application Server 7.1.1\\standalone\\deployments\\myProject.war\\WEB-INF\\classes\\aaa\\bbb\\ccc\\ddd

  2. getClass().getClassLoader().getResource(".").getPath(); --> this returns: C:\\Tools\\JBoss Application Server 7.1.1\\modules\\sun\\jdk\\main\\service-loader-resources , which is completely irrelevant. ->返回: C:\\Tools\\JBoss Application Server 7.1.1\\modules\\sun\\jdk\\main\\service-loader-resources ,这是完全不相关的。

I want something to return C:\\Tools\\JBoss Application Server 7.1.1\\standalone\\deployments\\myProject.war\\WEB-INF\\classes 我想要一些东西来返回C:\\Tools\\JBoss Application Server 7.1.1\\standalone\\deployments\\myProject.war\\WEB-INF\\classes

If it is not possible, I will get the first path and go as many folders back as needed to reach classes folder. 如果不可能,我将获得第一个路径,并根据需要返回尽可能多的文件夹以到达classes文件夹。

Thank you. 谢谢。

您需要ServletContext.getRealPath(String)方法。

getServletContext().getRealPath("/WEB-INF")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM