【问题标题】:How to load resource file in jenkins plugin?如何在 jenkins 插件中加载资源文件?
【发布时间】:2018-04-25 12:33:09
【问题描述】:

我正在尝试加载 src/main/resources 文件夹中的资源文件作为 Jenkins 插件的一部分。它总是给我 FileNotFoundException。有人可以解释一下如何使它工作吗?

异常信息:

java.io.FileNotFoundException: file:/var/lib/jenkins/plugins/Report/WEB -INF/lib/Report.jar!/properties.txt (No such file or directory)

【问题讨论】:

  • 您是如何访问资源的?我假设您正在通过 File(...) 访问它?如果是这样,这完全是错误的..您必须改用getClass().getResourcesAsStream("/...")...
  • 我正在使用 getClass().getResourcesAsStream("/...") 但它仍然给了我异常

标签: maven jenkins jenkins-plugins


【解决方案1】:

很久以前就问过这个问题,但我只是想分享我的答案,以防它帮助遇到与我类似的问题的人。

按照以下步骤操作:它适用于我的情况:

  1. 将您的文件放在“资源”文件夹中,该文件夹通常位于 路径“src/main/resources”。在 IntelliJ IDE 中,标记资源 目录作为“资源根”。
  2. 由于文件放置在资源中,因此它们位于目录中 那是在构建路径上,所以 Maven 应该能够在没有的情况下加载它 设置额外的构建路径。
  3. 假设文件名为“application-env.properties”。以下代码块应该 在 jenkins 插件运行时从资源文件夹中提取文件。

        InputStream inputStream = null;
        try{
          String resourceName = "application-env.properties";
          Properties props = new Properties();
          ClassLoader cl = <NameOfThisClass>.class.getClassLoader();
          try (InputStream stream = cl.getResourceAsStream(resourceName)) {
            props.load(stream);
          }
          //read props or return the same to the caller
        } 
        finally {
          if (inputStream != null) {
            inputStream.close();
          }
        }        
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-22
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 2011-03-27
    相关资源
    最近更新 更多