这是我的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-group:my-artifact:1.0 JAR文件中。
发布于 2011-03-07 14:33:42
答案很简单:
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-02-24 19:06:07
如果文件在Jar中,那么从技术上讲,它不是一个文件,而是一个Jar条目。这意味着你有这些可能性:
InputStream使用ClassLoader或手动Jar processing发布于 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或类似库中的内容来完成此操作:
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()
}https://stackoverflow.com/questions/5102462
复制相似问题