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.txtにあります。my-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

settings.localRepositoryjarから外部リポジトリへのパスを解決する方法はわかりませんが、jarがローカルリポジトリにあると仮定すると、暗黙の変数を介してそれにアクセスできるはずです。次に、グループとアーティファクトIDをすでに知っているので、この場合はjarへのパスは次のようになります。settings.localRepository + "/my-group/my-artifact/1.0/my-artifact-1.0.jar"

このコードを使用すると、jarファイルを読み込んで、そこからテキストファイルを取得できます。私は通常、ファイルをbyte []に​​読み込むためにこのコードを書くことはないことに注意してください。完全を期すために、ここに置いています。理想的には、ApacheCommonsまたは同様のライブラリからの何かを使用してそれを行います。

    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 に答える
0

ファイルがJarにある場合、技術的にはファイルではなく、Jarエントリです。つまり、次のような可能性があります。

于 2011-02-24T11:06:07.293 に答える