14

How to compile all files in directory to *.class files?

1
  • 1
    1) see makefile (or ant or maven or ....) 2) No
    – KevinDTimm
    Mar 1, 2010 at 14:35

3 Answers 3

25

Well, this seems pretty obvious, so I may be missing something

javac *.java

(With appropriate library references etc.)

Or perhaps:

javac -d bin *.java

to javac create the right directory structure for the output.

Were you looking for something more sophisticated? If so, could you give more details (and also which platform you're on)?

8
  • what about all java files in all sub and decending directories?
    – Tom
    Feb 9, 2011 at 19:17
  • @Tom: Find that would depend on the operating system. It's dead easy on Unix, using find. Harder on Windows.
    – Jon Skeet
    Feb 9, 2011 at 19:20
  • 4
    so I may be missing something: Yes, one should not be inside the package directory when compiling, since then classes not explicitely named on the command line can't be found (i.e. these in other packages and not included in the compiler's bootstrap path). javac super/package/dir/*.java would be the right way to do it (maybe adding -d, -cp, and/or -sourcepath). Jul 4, 2011 at 23:16
  • This is probably incomplete, because I get "javac: file not found: *.java" on Windows 7. Feb 12, 2016 at 15:58
  • @TomášZato: That just means you haven't got any .java files in the current directory. It's hard to compile source code when there aren't any source files...
    – Jon Skeet
    Feb 12, 2016 at 16:00
10

Yet another way using "find" on UNIX is described here:

http://stas-blogspot.blogspot.com/2010/01/compile-recursively-with-javac.html

The following two commands will compile all .java files contained within the directory ./src and its subdirectories:

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

First, find generates sources_list.txt, a file that contains the paths to the Java source files. Next, javac compiles all these sources using the syntax @sources_list.txt.

2
3

Here's a code fragment that I use to build an entire project where, as usual, source files are in a deeply nested hierarchy and there are many .jar files that must go into the classpath (requires UNIX utilities):

CLASSPATH=
for x in $(find | grep jar$); do CLASSPATH="$CLASSPATH:$x"; done
SRC=$(find | grep java$)
javac -cp "$CLASSPATH" $SRC

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.