Build a executable jar file using external jars:
$ find .
./Mod1.java
./mf
./lib
./lib/commons-io-2.4.jar
$ cat Mod1.java
import org.apache.commons.io.FileUtils;
import java.io.File;
public class Mod1 {
public static void main (String[] args) {
String[] scriptExt = new String[] { "scala" };
System.out.println("List all scala files: " + FileUtils.listFiles(new File("/home/chad/docs/tmp"), scriptExt, false));
}
}
$ cat mf
Class-Path: lib/commons-io-2.4.jar
Main-Class: Mod1
$ javac -cp lib/* Mod1.java
$ jar cfm pkg.jar mf Mod1.class
$ java -jar pkg.jar
List all scala files: [/home/chad/docs/tmp/sf2.scala, /home/chad/docs/tmp/lookup.scala, /home/chad/docs/tmp/spark-filter.scala, /home/chad/docs/tmp/hw.scala, /home/chad/docs/tmp/newDel.scala, /home/chad/docs/tmp/scalaTime.scala, /home/chad/docs/tmp/sf3.scala]
Note that classpath wildcard can't be used in manifest file (here is mf), which means "Class-Path: lib/*" doesn't work. See 5 things you didn't know about ... JARs for explanations.
The "-cp" option or "CLASSPATH=..." is invalid in java -jar xxx.jar
.
So if you don't want to create manifest file by hand, run java program with java -cp ... MainClass
:
$ tree
.
├── com
│ └── boco
│ └── example
│ └── Example.java
└── lib
└── commons-io-2.4.jar
4 directories, 2 files
$ cat com/boco/example/Example.java
package com.boco.example;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.util.Collection;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;
public class Example {
public static void main (String[] args) {
Collection<File> found = FileUtils.listFiles(new File("."), TrueFileFilter.INSTANCE, DirectoryFileFilter.DIRECTORY);
System.out.println("List files with apache-commons.FileUtils:");
for (File f : found) {
System.out.println(f);
}
System.out.println("--- OVER ---");
}
}
$ javac -cp lib/commons-io-2.4.jar com/boco/example/Example.java
$ jar cf example.jar com
$ mv example.jar lib
$ tree
.
├── com
│ └── boco
│ └── example
│ ├── Example.class
│ └── Example.java
└── lib
├── commons-io-2.4.jar
└── example.jar
4 directories, 4 files
$ java -cp "lib/*" com.boco.example.Example
List files with apache-commons.FileUtils:
./com/boco/example/Example.java
./com/boco/example/Example.class
./lib/example.jar
./lib/commons-io-2.4.jar
--- OVER ---