我只是好奇为什么在像我这样的某些系统上,我必须使用 java -cp 。并且简单地在终端窗口中使用 java 命令不起作用?
2 回答
When you are launching a JVM using the java
command, the JVM's classpath is determined as follows:
If you use the "-jar" option, then the classpath consists of the JAR file itself, and together with the optional "Classpath" attribute in the JAR file.
Otherwise, if you use the "-cp" option, the option's value gives the classpath
Otherwise, if the CLASSPATH environment variable is set, then that gives the classpath
Otherwise, the classpath consists of just the current directory; i.e. ".".
Now you say that you have to explicitly give "-cp ." in order for the java
command to execute your commands correctly.
The most likely explanation is that you have the CLASSPATH environment variable set to something inappropriate. When you run a java MyClass
, it will be looking on the classpath specified by CLASSPATH ... and failing. But when you add "-cp .", you are saying "ignore CLASSPATH and just look in the current directory".
选项 -cp 用于添加 Java 环境仅为该执行加载的目录或文件的路径。这些文件“将包含对您在程序中使用的库的引用”。或者,要使用 -cp,您可以永久设置类路径。设置方式取决于您使用的操作系统。更多信息在这里:http ://docs.oracle.com/javase/tutorial/essential/environment/paths.html