Compile source file to a different directory?

Jonathan Lam picture Jonathan Lam · Aug 25, 2013 · Viewed 28k times · Source

Is there a way to compile a Java source file (*.java) to a different directory?

If my package file structure is like so:

Mathematics ->
  Formulas ->
    src ->
      // source files containing mathematical formulas...
    bin ->
      // class files containing mathematical formulas...
  Problems ->
    src ->
      // source files containing mathematical problems...
    bin ->
      // class files containing mathematical problems...

I want to separate source and class files to keep the folders organized, but I currently have to copy all the class files from the src folders to the bin folders after every compile.

Is there a way to simplify this process by compiling the class files to another folder in the javac command?

Answer

Jon Skeet picture Jon Skeet · Aug 25, 2013

Yup, absolutely - use the -d option to specify the output directory:

javac -d bin src/foo/bar/*.java

Note that the directory you specify is the root of the output structure; the relevant subdirectories will be created automatically to correspond to the package structure of your code.

See the javac documentation for more details.

In this case you'd need to issue one javac command to compile the formulae, and another to compile the problems though - potentially using the formulae bin directory as part of the classpath when compiling the problems.

(You might want to consider using a single source structure but different packages, mind you. You should also consider using an IDE to hide some of this complexity from you - it ends up getting tiresome doing all of this by hand, even though it's not actually hard.)