Search code examples
javacommand-line

Java - using a downloaded package without IDE


I am quite new to Java. I am still developing with a simple text editor to better understand how the inclusion of packages works for Java.

I have my file Test.java, whose first two lines are:

import java.util.List;  
import com.google.gson.Gson;

I have tried to download the package google-gson and unzip it in the same directory where Test.java is.

|-- google-gson-1.5
|   |-- gson-1.5.jar
|   |-- gson-1.5-javadoc.jar
|   |-- gson-1.5-sources.jar
|   |-- LICENSE
|   `-- README
`-- Test.java

But when I try to launch:

javac Test.java

I get this error message:

Test.java:2: package com.google.gson does not exist
import com.google.gson.Gson;

What should I do to make things work (using the command line and a simple editor)?

Thanks, Dan


Solution

  • Assuming Test.java is not assigned to a package:

    Compile:

    javac -cp .;google-gson-1.5\gson-1.5.jar Test.java
    

    Run:

    java -cp .;google-json-1.5\gson-1.5.jar Test
    

    If you want to add more JARs:

    javac -cp .;google-gson-1.5\gson-1.5.jar;anotherlib\anotherlib.jar Test.java
    

    (Note: Windows syntax shown. On *Nix systems, use : instead of ; and / instead of \)

    As long as you intend on using the javac and java command line interfaces directly, I recommend creating a build.bat and a run.bat (or build.sh and run.sh on *Nix) to store the javac and java incantations that you compose. These scripts make it easier to:

    1. remember the correct build/run command structure several days later
    2. send a ready-to-build/ready-to-run copy of the project to someone else
    3. let you edit the commands in a text editor, rather than on the command line

    Ant: Once you are comfortable with using java and javac on the command line and through shell scripts, it might be time to investigate migrating to Ant's powerful framework, which is great for maintaining all your build, test, and run configurations.

    More recently, Apache Maven and Apache Ivy have become more popular than Ant. You might like to look into those as well.