Building Java Archive (.jar) Files: the Jar Builder

After building the class files, it's common to collect them into a Java archive (.jar) file, which you do by calling the Jar Builder method. If you want to just collect all of the class files within a subdirectory, you can just specify that subdirectory as the Jar source:

      Java(target = 'classes', source = 'src')
      Jar(target = 'test.jar', source = 'classes')
    

SCons will then pass that directory to the jar command, which will collect all of the underlying .class files:

      % scons -Q
      javac -d classes -sourcepath src src/Example1.java src/Example2.java src/Example3.java
      jar cf test.jar classes
    

If you want to keep all of the .class files for multiple programs in one location, and only archive some of them in each .jar file, you can pass the Jar builder a list of files as its source. It's extremely simple to create multiple .jar files this way, using the lists of target class files created by calls to the Java builder as sources to the various Jar calls:

      prog1_class_files = Java(target = 'classes', source = 'prog1')
      prog2_class_files = Java(target = 'classes', source = 'prog2')
      Jar(target = 'prog1.jar', source = prog1_class_files)
      Jar(target = 'prog2.jar', source = prog2_class_files)
    

This will then create prog1.jar and prog2.jar next to the subdirectories that contain their .java files:

      % scons -Q
      javac -d classes -sourcepath prog1 prog1/Example1.java prog1/Example2.java
      javac -d classes -sourcepath prog2 prog2/Example3.java prog2/Example4.java
      jar cf prog1.jar classes/Example1.class classes/Example2.class
      jar cf prog2.jar classes/Example3.class classes/Example4.class