我以前从来没有遇到过这个问题,当我去运行 Java 程序(在终端中)时,我会简单地说,
java className
然后程序就会运行。但是最近当我尝试这个时我得到了错误,
could not find or load main class className
为了解决这个问题,我一直在将我当前的工作目录添加到类路径中,然后程序运行。我不确定要将什么添加到我的环境变量中,以便当前工作目录始终在类路径上,从而避免这个更长的脚本,
java -cp ./ className
根据 this StackOverflow 发布了 Oracle 的标准实现,首先在当前工作目录中查找类名。
(我使用的是 Java 8 和 Windows 8.1)
最佳答案
类路径,如果在命令行中找不到,并且在CLASSPATH
环境变量中找不到,defaults to the current directory .
-cp classpath
Specifies a list of directories, JAR files, and ZIP archives to search for class files. Separate class path entries with semicolons (;)
Specifying -classpath or -cp overrides any setting of the CLASSPATH environment variable.
If -classpath and -cp are not used and CLASSPATH is not set, then the user class path consists of the current directory (.).
如果您指定-cp
,那么您必须在类路径中显式包含.
(当前目录),否则它不会被包含。
如果不使用 -cp
不起作用,但显式声明 -cp .
确实有效,那么您必须具有 CLASSPATH
环境定义的变量,它不能显式包含 .
。这可以解释为什么通过包含 .
和 -cp
选项来覆盖 CLASSPATH
是有效的。
关于java - -cp ./为什么我在运行 Java 时总是必须手动将 CWD 包含到 CP 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25818550/