这是我的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>
[...]
my-file.txt
位于my-group:my-artifact:1.0
JAR文件中。
答案 0 :(得分: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
其余的都是微不足道的。
答案 1 :(得分:0)
如果文件在Jar中,那么它在技术上不是文件,而是Jar条目。这意味着你有这些可能性:
InputStream
ClassLoader或手动Jar处理dependency:unpack
或dependency:unpack-dependencies
)答案 2 :(得分: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()
}