I am using the javac compiler to compile java files in my project. The files are distributed over several packages like this: com.vistas.util
, com.vistas.converter
, com.vistas.LineHelper
, com.current.mdcontect
.
Each of these packages has several java files. I am using javac like this:
javac com/vistas/util/*.java com/vistas/converter/*.java
com.vistas.LineHelper/*.java com/current/mdcontect/*.java
(in one line)
Instead of giving so many paths, how can I ask the compiler to compile recursively all the java files from the parent com directory?
javac -cp "jar_path/*" $(find . -name '*.java')
(I prefer not to use xargs because it can split them up and run javac multiple times, each with a subset of java files, some of which may import other ones not specified on the same javac command line)
If you have an App.java entrypoint, freaker's way with -sourcepath is best. It compiles every other java file it needs, following the import-dependencies. eg:
javac -cp "jar_path/*" -sourcepath src/ src/com/companyname/modulename/App.java
You can also specify a target class-file dir: -d target/
.
find . -name "*.java" -print | xargs javac
Kinda brutal, but works like hell. (Use only on small programs, it's absolutely not efficient)
I'm just using make with a simple makefile that looks like this:
JAVAC = javac -Xlint:unchecked
sources = $(shell find . -type f -name '*.java')
classes = $(sources:.java=.class)
all : $(classes)
clean :
rm -f $(classes)
%.class : %.java
$(JAVAC) $<
It compiles the sources one at a time and only recompiles if necessary.
I've been using this in an Xcode JNI project to recursively build my test classes:
find ${PROJECT_DIR} -name "*.java" -print | xargs javac -g -classpath ${BUILT_PRODUCTS_DIR} -d ${BUILT_PRODUCTS_DIR}
In the usual case where you want to compile your whole project you can simply supply javac with your main class and let it compile all required dependencies:
javac -sourcepath . path/to/Main.java
javac command does not follow a recursive compilation process, so you have either specify each directory when running command, or provide a text file with directories you want to include:
javac -classpath "${CLASSPATH}" @java_sources.txt
If your shell supports it, would something like this work ?
javac com/**/*.java
If your shell does not support **
, then maybe
javac com/*/*/*.java
works (for all packages with 3 components - adapt for more or less).
I would advice you to learn using ant, which is very-well suited for this task and is very easy to grasp and well documented.
You would just have to define a target like this in the build.xml file:
<target name="compile">
<javac srcdir="your/source/directory"
destdir="your/output/directory"
classpath="xyz.jar" />
</target>
Source: Stackoverflow.com