7

I have a folder on my desktop titled "Stuff" and in that folder I have the following:

  • Hello.java
  • mail.jar

And Hello.java imports from mail.jar, so I need to tell Hello.java to look for mail.jar.

From a Windows command line and from a unix command line, how can I compile this and run this?

3 Answers 3

14

Compile:

javac -cp .;mail.jar Hello.java

where ; is for Windows; use : for *nix.

and run:

java -cp .;mail.jar Hello

where again, use ; for Windows and : for *nix.

-cp tells both javac and java what classpath to use, and as your files are in the local directory where you're executing the command, you can use . for the Hello part and the name of the jar for the paths inside the jar. Wikipedia has a decent article on classpaths.

Mind you, if you're going to be doing this on a regular basis, you may want to set your CLASSPATH environment variable rather than constantly using the -cp flag. Both java and javac use the CLASSPATH variable.

For my own development machine, I actually include . in my CLASSPATH variable, for convenience. It's not something I would do on a production or build/test box, but it's very handy for development purposes. You'd want to have your usual jars in it as well.

Sign up to request clarification or add additional context in comments.

2 Comments

This will not make Java pick up the JAR file.
@Jesper: Thanks, I think I was fixing that as you commented. :-) I'd kind of forgotten the jar.
2

Assuming Hello.java does not contain a package declaration, on Windows:

javac -cp mail.jar Hello.java
java -cp mail.jar;. Hello

The only difference on Unix platforms is that you separate the elements of the classpath with a scolon instead of a semicolon:

java -cp mail.jar:. Hello

Comments

-1

Follow this tutorial and you should be able to do it in no time:

Java Compilation

You also shouldn't have any problems with the classpath because your classes are in the same folder

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.