nbro
nbro

Reputation: 15837

Compiling a java file using javac and the command line

I am trying to learn more about javac and how to use developer tools for Java using the command line.

As far as I understood, the option -classpath is needed to specify the path where javac searches for our classes and resource files, if we are not in the current directory, because usually the class path is set to our current working directory.

This is my current working directory:

/Users/user1/Desktop

And I am trying to compile a .java file which is in:

/Users/user1/Desktop/PF/

and the file is called MainClass.java.

I am trying to compile it using the following command:

javac -classpath /PF MainClass.java

But it does not seem to work, in fact I keep receiving the following:

javac: file not found: MainClass.java
Usage: javac <options> <source files>
use -help for a list of possible options

What am I doing wrong?

Upvotes: 3

Views: 6847

Answers (4)

Bruce
Bruce

Reputation: 8849

-classpath

Specifies the path javac uses to look up classes needed to run javac or being referenced by other classes you are compiling. Overrides the default or the CLASSPATH environment variable if it is set. Directories are separated by colons. It is often useful for the directory containing the source files to be on the class path. You should always include the system classes at the end of the path.

class path is used to specify the compiled sources that need to be used in your class. For example in this code if you are accessing another class then you should specify the location of the compiled sources of the that class.

In your case if don't have any class dependency then simply remove classpath option and compile using[navigate inside folder]

javac Mainclass.java

Upvotes: 0

SCS
SCS

Reputation: 121

Remove the -classpath. And if you are in the place where the java file is required (which currently you arent) you can remove that PF/ too.

Upvotes: -1

K139
K139

Reputation: 3669

Classpath is for .class files, not for .java files.

javac command needs correct path to the .java file to compile it. So

javac ./PF/MainClass.java

Will create the class file in current directory.

If your MainClass.java depends on any class files to compile correctly, then you put those class/jar files in classpath.

Upvotes: 3

Kevin Workman
Kevin Workman

Reputation: 42176

That isn't how the classpath works. You use the classpath to point to classes that your Java file needs in order to compile. You don't use the classpath to point to the Java file itself.

Either go into the PF directory and do this:

javac MainClass.java

That will create the MainClass.class file inside the PF directory. If instead you want to create the MainClass.class file on your desktop, then from your desktop, do this:

javac PF/MainClass.java

Upvotes: 1

Related Questions