2

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

[...]
<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-file.txtmy-group:my-artifact:1.0

4

3 回答 3

2

答案很简单:

def url = getClass().getClassLoader().getResource("my-file.txt");

然后 URL 将采用以下格式:

jar:file:/usr/me/.m2/repository/grp/art/1.0-SNAPSHOT/art.jar!/my-file.tex

其余的都是微不足道的。

于 2011-03-07T06:33:42.487 回答
0

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

于 2011-02-24T11:06:07.293 回答
0

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

此代码应允许您读取 jar 文件并从中获取文本文件。注意我通常不会自己编写这段代码来将文件读入 byte[],我只是为了完整起见把它放在这里。理想情况下使用来自 apache commons 或类似库的东西来做到这一点:

    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()
    }
于 2011-03-03T04:33:45.707 回答