Reputation: 1358
I want to build a jar file using ant. I have a resource folder in my project with files and folder beneath. Example:
Package---
src
Main.java
resources
images
logo.png
Inside the JAR file the images sould be accesible via ...File("resources/images/logo.png");
is that possible and if yes how?
I tried serveral options but could not figure out how it works. One of my attempts:
...
<zipfileset dir="${dir.buildfile}/ressources/images" includes="*.png"/>
<zipfileset dir="${dir.buildfile}/ressources/images" includes="*.jpg"/>
...
This wasn't working...
Best regards!
Upvotes: 0
Views: 44
Reputation: 17422
Here's a simple example. Let's say you have the following directory structure:
./Test.java
./Test.class
./resources/test.txt
where your source file accesses the file resources/test.txt
like so:
import java.io.*;
import java.net.*;
public class Test {
public void test() throws IOException, URISyntaxException {
URL url = getClass().getResource("/resources/test.txt");
try (BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream()))) {
for (String line; (line = br.readLine()) != null;) {
System.out.println("> " + line);
}
}
}
public static void main(String[] args) throws Exception {
Test test = new Test();
test.test();
}
}
Then the following ANT target will create a jar file that contains the .class
file and the resources
directory:
<target name="jar">
<jar destfile="test.jar">
<fileset dir="." includes="Test.class"/>
<fileset dir="." includes="resources/**"/>
</jar>
</target>
You can verify that by running:
java -cp test.jar Test
Two things should be noted:
/
at the beginning of the path in the getClass().getResource(...)
call. This is important because otherwise the package name of the class would be prepended to the given path (although in the example above, Test.java does not have a package declaration).Upvotes: 1