简体   繁体   English

Java-从不同的Maven模块读取文件

[英]Java - read files from different maven modules

I have an application consisting of three modules: Module A, Module B and Module C (which is a web module). 我有一个包含三个模块的应用程序:模块A,模块B和模块C(这是一个Web模块)。 I am using Maven to build the application. 我正在使用Maven构建应用程序。

I have the following logic implemented: Module A is included in Module B using a maven dependency and Module B is included in Module C, also by using a dependency (I have separate pom files for each module). 我实现了以下逻辑:使用maven依赖项将模块A包含在模块B中,并且也通过使用依赖项将模块B包含在模块C中(每个模块都有单独的pom文件)。 Module C is the one that gets deployed. 模块C是被部署的模块。

In Module CI want to have a folder called files, that would contain some content files. 在Module CI中,希望有一个名为files的文件夹,其中将包含一些内容文件。 This particular folder would be located under the webapp folder. 该特定文件夹将位于webapp文件夹下。 I want to be able to read these files in Module B. 我希望能够读取模块B中的这些文件。

Is there a way to do this? 有没有办法做到这一点? I have tried reading files with getClass().getResourceAsStream("files/file_name") but the returned value was null. 我尝试使用getClass()。getResourceAsStream(“ files / file_name”)读取文件,但返回的值为null。

Most clean solution: 最干净的解决方案:

  • Create a new module D . 创建一个新的模块D
  • Put the files into D/src/main/resources/WEB-INF/ 将文件放入D/src/main/resources/WEB-INF/
  • Add D as a dependency to B D添加为对B的依赖

That makes the files available to B as resource on the classpath while keeping them mostly separate from everything else. 这使得文件可以作为类路径上的资源供B ,同时又使它们与其他所有文件分开。 Note that to get the files, you have to use 请注意,要获取文件,您必须使用

getClass().getResourceAsStream("/WEB-INF/...");

otherwise Java will try to load them relative to the current class. 否则,Java将尝试相对于当前类加载它们。

Be careful that you don't have file in C and D with the same names. 请注意, CD中没有相同名称的文件。 If you do, then it can be somewhat random which file Java will pick. 如果这样做,那么Java选择哪个文件可能会有些随机。

You should consider to put all these files into /src/main/resources directory in order to allow these files being in the application classpath when it is deployed. 您应该考虑将所有这些文件放到/src/main/resources目录中,以便在部署时将这些文件放在应用程序类路径中。 So, you can consider from your B module that all those files are available in the classpath. 因此,您可以从B模块中考虑所有这些文件在类路径中都可用。

Obviously, you have to take in consideration to copy those files in the /src/main/resources module B's directory. 显然,您必须考虑将这些文件复制到/src/main/resources模块B的目录中。

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

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