首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从GMaven脚本中加载/查找JAR资源?

如何从GMaven脚本中加载/查找JAR资源?
EN

Stack Overflow用户
提问于 2011-02-24 17:03:04
回答 3查看 707关注 0票数 2

这是我的gmaven脚本,它试图查找并加载位于提供的依赖项(它是pom.xml的一部分)中的某个位置的文件:

代码语言:javascript
复制
[...]
<plugin>
  <groupId>org.codehaus.gmaven</groupId>
  <artifactId>gmaven-plugin</artifactId>
  <executions>
    <execution>
      <configuration>
        <source>
          <![CDATA[
          def File = // how to get my-file.txt?
          ]]>
        </source>
      </configuration>
    </execution>
  </executions>
  <dependencies>
    <dependency>
      <groupId>my-group</groupId>
      <artifactId>my-artifact</artifactId>
      <version>1.0</version>
    </dependency>
  </dependencies>
</plugin>
[...]

JAR位于my-group:my-artifact:1.0 JAR文件中。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-03-07 14:33:42

答案很简单:

代码语言:javascript
复制
def url = getClass().getClassLoader().getResource("my-file.txt");

则URL将采用以下格式:

代码语言:javascript
复制
jar:file:/usr/me/.m2/repository/grp/art/1.0-SNAPSHOT/art.jar!/my-file.tex

剩下的都是微不足道的。

票数 2
EN

Stack Overflow用户

发布于 2011-02-24 19:06:07

如果文件在Jar中,那么从技术上讲,它不是一个文件,而是一个Jar条目。这意味着你有这些可能性:

  • 将其作为InputStream使用ClassLoader或手动Jar processing
  • Extract加载到文件中(可能使用ClassLoader或Jar
票数 0
EN

Stack Overflow用户

发布于 2011-03-03 12:33:46

我不确定如何将jar的路径解析为外部存储库,但假设jar在您的本地存储库中,那么您应该可以通过settings.localRepository隐式变量访问它。然后,您已经知道了您的组和工件id,因此jar的路径在本例中为settings.localRepository + "/my-group/my-artifact/1.0/my-artifact-1.0.jar"

这段代码应该允许您读入jar文件并从中获取文本文件。请注意,我通常不会自己编写此代码来将文件读入byte[],我只是出于完整性考虑而将其放在这里。理想情况下,使用apache commons或类似库中的内容来完成此操作:

代码语言:javascript
复制
    def file = null
    def fileInputStream = null
    def jarInputStream = null
    try {
        //construct this with the path to your jar file. 
        //May want to use a different stream, depending on where it's located
        fileInputStream = new FileInputStream("$settings.localRepository/my-group/my-artifact/1.0/my-artifact-1.0.jar")
        jarInputStream = new JarInputStream(fileInputStream)

        for (def nextEntry = jarInputStream.nextEntry; (nextEntry != null) && (file == null); nextEntry = jarInputStream.nextEntry) {
            //each entry name will be the full path of the file, 
            //so check if it has your file's name
            if (nextEntry.name.endsWith("my-file.txt")) {
                file = new byte[(int) nextEntry.size]
                def offset = 0
                def numRead = 0
                while (offset < file.length && (numRead = jarInputStream.read(file, offset, file.length - offset)) >= 0) {
                  offset += numRead
                }
            }
        }
    }
    catch (IOException e) {
        throw new RuntimeException(e)
    }
    finally {
        jarInputStream.close()
        fileInputStream.close()
    }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5102462

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档