Saturday, June 22, 2013

How to compile and run Java source codes from command-line on Linux

This tutorial tries to cover the missing part of javac usage description. You can find other examples of basic usage for javac, but not for complicated tasks.

Note: normally, all the sources would be located inside the src folder. This is a bit exaggerated example with an external org.example class, just to show how can it work even with that one.


Let's take the following directory structure:
We have the file Basis.java (package com.minthaka.alfa), which depends on the classes:
-Alien (package org.example)
-Additiv (package com.minthaka.beta)
-Exti (package lib)

We will compile all of these dependencies to a destination folder classes which is currently empty:

Open terminal in project's root folder and type:
javac -d classes -cp .:src src/com/minthaka/alfa/Basis.java

I have 3 packages:
- org.example, which is at the root of the project i need to include the root folder to the classpath. So I did start with a dot . (like -cp .:src)
- the two others are located in the subfolder src, so I added that to the classpath:
-cp .:src

I told the compiler to send the class files to the -d destination, which is currently the subfolder classes.

The last part of the command is a relative path to the main class called Basis.java.

Let's see what we got:
The folder classes isn't empty anymore. The compiler did create the entire dependency structure for the Basis.java.

The Basis.class is now ready to be run.

I will show two ways of running the file:

A. From inside the project's root:

java -cp classes com.minthaka.alfa.Basis

Since the classes contains all that Basis needs, it works seamlessly.

B. From any opened terminal:

java -cp /home/minthaka/javler/classes com.minthaka.alfa.Basis

This time we used absolute path to the classes folder. (Obviously the project's root folder is /home/minthaka/javler).


Finally, let's see the most tricky task of compiling the Basis.java from anywhere:


javac -d /home/minthaka/javler/classes -cp /home/minthaka/javler:/home/minthaka/javler/src /home/minthaka/javler/src/com/minthaka/alfa/Basis.java

For green: absolute path to the destination
For blue: absolute paths for each and every class
For pink: absolute path to the Basis.java