Thursday, January 21, 2010

Compile recursively with javac

To my shame I have never used javac directly for compiling source files, always it was something like "ant". And today it was the first time on my memory when I had to do that :) It was a simple application, just an example for presentation and I didn't want to add anything additional there.
Thing which looks like a trivial task appeared to be not so trivial, because javac doesn't recursively compile files in directories, you have to specify each directory separately or create file with list of files for compilation, something like that:

find ./src -name "*.java" > sources_list.txt
javac -classpath "${CLASSPATH}" @sources_list.txt

On Windows first line should be replaced with: dir .\src\*.java /s /B > sources_list.txt


phil pirj said...

Shame on you again! ;)

javac -classpath "${CLASSPATH} -sourcepath src
should do the same, and it's recursive by default

Stas said...

try first :)

lauren said...

It often become funny when you underestimate something.we think that we can do it in minutes but when we start doing it then we come to know that how much need to be done but their are always shorthands which we never used so never knew.
electronic signature

Carmelo said...

And if I have any subdirectory with other files to compile?
Recursive: what does this word mean?

Sorry for my english! :P

Stas said...

This will work. That's the point ;)

Stanislav Kobylansky said...

That true, and often the simplest things are hardest :)

Angel Villafranca said...

have you tried it?
are you sure that you don't get a nice:

javac: no source files
Usage: javac
use -help for a list of possible options

Guest said...

works like a charm! thank you

Hristo Hristov said...

a little bit late, but... :)

thanks for the tip!

*.java should be "*.java" in quotes or it will not work if there are .java files in the current directory as they are expanded by the shell

also, you can write the same as "find -name "*.java" | xargs javac -classpath "${CLASSPATH}" without using temporary file

karthikkannan M said...

along with sourcepath you got to mention a java file name(s) to compile. From sourcepath, the compiler takes the java files on need basis. So, it is not recursive... just slightly better... I think there must be a better solution built in Jdk itself... for a platform which is more than 15 years old...