Compiling from the command line

拟墨画扇 提交于 2021-02-16 17:56:34

问题


I'm trying to understand how works the option -classpath when compiling from command line.

I try from parent of mydirectory:

javac -cp mydirectory/subdir Hello.java

But compiler says:

javac: no sources files

How does -cp (-classpath) work?? What am I doing wrong?

If I make it from subdir directory:

javac Hello.java

then compiles properly.


回答1:


javac TestProgram1.java TestProgram2.java TestProgram3.java

You can use a wildcard to compile all the files in a folder, like this:

javac *.java

If you need to compile a lot of files at the same time but don’t want to use a wildcard (perhaps you want to compile a large number of files but not all the files in a folder), you can create an argument file, which lists the files to compile. In the argument file, you can type as many filenames as you want, using spaces or line breaks to separate them. Here’s an argument file named TestPrograms that lists three files to compile:

TestProgram1.java
TestProgram2.java
TestProgram3.java

You can compile all the programs in this file by using an @ character, followed by the name of the argument file on the javac command line, like this:

javac @TestPrograms

-cp and -classpath

Specifies where to find user class files. Use this option if your program makes use of class files that you’ve stored in a separate folder.




回答2:


The files you are compiling must be defined directly

For example, if you are in the parent folder:

javac subdir/Hello.java

would be needed to compile.

The classpath allows finding .class files that are needed to compile things defined as above.

For example, if in the code you had a reference to the class "Birds" and that class was in a jar named "animals.jar" in the current folder, which was the parent of where the java file was, you would need this:

javac -cp animals.jar subdir/Hello.java



回答3:


javac XXX.java

Command used to compile java class , where as -classpath flag is available with java command.

we run java program by using

java XXX.class

here to start with main() function, JVM should know where the class file is. so to specify path of class we use classpath flag

Classpath link to get more details.

some example for runing java program are

java -classpath .;yourJarFile.jar your.MainClass

 java -classpath path_till_classfile/HelloWorld


来源:https://stackoverflow.com/questions/17952801/compiling-from-the-command-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!