【问题标题】:Maven module dependency and resourcesMaven 模块依赖和资源
【发布时间】:2014-09-23 11:12:03
【问题描述】:

我有一个maven项目说ProjectA,并且这个项目中有一个类说ClassA,它使用资源文件夹中的文件,我使用以下方式从资源中读取:

String fileName = IPToGeoMapper.class.getResource("/resourceFile.txt").getFile();
File resourceFile = new File(fileName);

它就像魅力一样。

现在,当我从这个项目中创建工件时(我尝试提取创建的 jar 并且它在 jar 中打包了 resourceFile.txt),并将其用作其他项目中的依赖项,比如 ProjectB,ClassA 不再找到resourceFile.txt,因为它试图浏览 ProjectB 的资源文件夹。

我想要最好的全局解决方案,它适用于我导入从 ProjectA 创建的工件的所有项目 处理这个问题的最佳方法是什么?

【问题讨论】:

  • 尝试使用 ResourceAsStream 从类路径加载它

标签: maven maven-resources-plugin


【解决方案1】:

试试这个方法,我以读取属性文件为例。

Properties propfile = new Properties(); propfile.load(PropertyUtils.class.getClassLoader() .getResourceAsStream( "applicationprops.properties"));

BufferedReader reader = new BufferedReader(new InputStreamReader(ClassA.class.getClassLoader().getResourceAsStream("file.txt"))); StringBuilder out = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { out.append(line); } System.out.println(out.toString()); //Prints the string content read from input stream reader.close();

【讨论】:

  • 是的,我认为这适用于属性文件作为它的返回流,我实际上需要处理文件。
  • 您仍然可以从流中读取文件内容。如果您必须阅读文件内容,请通过从流中读取文件内容来编辑我的答案。
猜你喜欢
  • 2010-10-22
  • 1970-01-01
  • 1970-01-01
  • 2020-09-16
  • 1970-01-01
  • 1970-01-01
  • 2015-06-23
  • 2019-11-04
  • 1970-01-01
相关资源
最近更新 更多