javacommand-linecompilationclasspathlibraries

Compiling .java files from the command line - external libraries, classpath


I made a project in Eclipse and am now trying to ensure that the .java files compile from the command line. I've been trying to compile using javac *.java in the folder with all my .java files. However, this results in errors due to a reference to a class from an external library, Joda-time. I have the following .classpath file that Eclipse made for the project but don't know what to do with it.

    <?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" path="src"/>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7"/>
    <classpathentry kind="lib" path="libs/joda-time-2.2.jar"/>
    <classpathentry kind="output" path="bin"/>
</classpath>

I tried compiling with javac -classpath *.java but this only generates more errors. My source files are inside a package folder inside a 'src' folder. Where do I put my classpath file and my joda-time-2.2.jar file, and how do i get everything to compile?

[edit] I'm using Windows 7


Solution

  • Judging by your .classpath file, this probably works:

    javac -d bin -cp libs/joda-time-2.2.jar src/your/package/*.java
    

    This assumes you run it in your project's directory.

    The -d flag tells javac where to put the output files. The -cp flag is a shorthand for -classpath. I got these parameters based on the .classpath file in your question.

    In general you can figure out what is needed by reading and understanding the errors in the output of javac. I bet you got many cannot find symbol errors at first, because the "symbols" were not on your classpath, so javac could not possibly know how to find them.

    It is very important to understand how to build your projects, it is fundamental knowledge and a core competency of programmers.

    Once you understand how to build manually like this, I recommend to look into build tools, preferably Maven, alternatively Ant that make building on the command line much easier. The majority of Java projects use these tools to build their products on the command line and in automated build systems, continuous integration, and so on.