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
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:
- remember the correct build/run command structure several days later
- send a ready-to-build/ready-to-run copy of the project to someone else
- 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.
In order to compiler your java program, you'll either need the sources in the folder that fits the packaged (for example com.google.gson package must be in com\google\gson folder)or you'll need to place your gson-1.5.jar in the Classpath [Explanation here].
I think setting the classpath via javac should be the recommended solution in this case.
精彩评论