In NetBeans, creating a runnable jar for your Scala program is even easier. It’s done automatically when you build your project. The compile output even reminds you how to run the jar file.
The first time I did it, I saw an error about finding a Scala object. Solve that by adding the scala-library.jar to your project. Right-click on the libraries folder in the Projects tab on the left sidebar. Choose Add JAR/Folder and find your scala-library.jar. Because I installed Scala with MacPorts, mine was under
/opt/local/var/macports/software/scala/2.7.4_0/opt/local/share/scala/lib
See this blog entry for more on finding MacPorts installations.
Add any other required libaries this way. Rebuild. Then you can run your program via
$ java -jar YourProgram
in the dist/ directory.
Note that by default, the NetBeans jar mechanism creates a jar file for your program and then adds the libraries you specified into a lib directory. So it’s not a single executable jar. You can then zip and distribute the jar/directory. The advantage of this approach is that you can update the libraries in the lib directory without having to rejar everything. You can probably also save space by using symbolic links in the lib directory to point to your jar locations. I haven’t tried that, though.
You can ignore the lib directory by directly linking to your libraries in the java command using Xbootclasspath. Here, I’ve added two libraries, Configgy and the Scala jar, to my project, but note that I also had to include the path to the Java SDK:
java -Xbootclasspath:/opt/local/var/macports/software/scala/2.7.4_0/opt/local/share/scala/lib/scala-library.jar:../configgy/dist/configgy-1.3/configgy-1.3.jar:/System/Library/Frameworks/JavaVM.framework/Versions/1.6/Classes/classes.jar -jar ScalaApplication1.jar
If you want to create a single jar with all of the required files, then add a few lines to your build.xml file. There are many varying pages on the web about this; I found these directions simplest:
1. Add
<target name="-pre-jar">
<unjar dest="${build.classes.dir}" src="${file.reference.theLibraryName.jar}">
</target>
to the build.xml file, replacing theLibraryName with the appropriate jar filename.
2. Rebuild
To get the correct library filename, switch to the Files tab in the left sidebar and look in the project.properties file. Find lines that look like these:
<unjar dest="${build.classes.dir}" src="${file.reference.configgy-1.3.jar}"/>
<unjar dest="${build.classes.dir}" src="${file.reference.scala-library.jar}"/>
You can ls -l your program in the dist directory and see that it’s much larger; it now contains the libraries. The lib directory is still there, but you don’t need it anymore.
Tags: NetBeans, runnable jar