简体   繁体   English

Java 中的 CLASSPATH 问题

[英]Issues with CLASSPATH in Java

I have an issue with setting up my Java dev environment.我在设置 Java 开发环境时遇到问题。 In the past,I have installed Java, then my IDE and went to coding.过去,我安装了Java,然后我的IDE,然后去编码。 I am now starting to setup my laptop to use command-line compiling and Notepad as my code editor.我现在开始设置我的笔记本电脑以使用命令行编译和记事本作为我的代码编辑器。 I am getting an error that I have tried to correct, but since this is my first time doing it this way, I am kinda lost.我收到了一个我试图纠正的错误,但由于这是我第一次这样做,我有点迷路了。

I run javac and it creates my.class file with no issue, but then I try to run the class file with the java A and it throws an error:我运行 javac 并创建 my.class 文件没有问题,但随后我尝试使用 java A 运行 class 文件并引发错误:

c:\workspace>java A Error: Could not find or load main class A Caused by: java.lang.ClassNotFoundException: A c:\workspace>java A 错误:无法找到或加载主 class A 原因:java.lang.ClassNotFoundException:A

My CLASSPATH is set to C:\Program Files\Java\jdk-14.0.1\lib我的 CLASSPATH 设置为 C:\Program Files\Java\jdk-14.0.1\lib

My code is:我的代码是:

class A
{
public static void main(String args[]){
    System.out.println("Hello World!");
}
}

Thanks in advance for any help.提前感谢您的帮助。

Using global environment variable CLASSPATH is a very bad idea.使用全局环境变量 CLASSPATH 是一个非常糟糕的主意。 It's possible to write more than one java program on a single machine, you know:)一台机器上可以写多个java程序,你懂的:)

To compile the code, javac A.java will do the job.要编译代码, javac A.java将完成这项工作。 To run it, assuming the A class has no package statement, the directory that contains the class file needs to be on the classpath.要运行它,假设 A class 没有 package 语句,则包含 class 文件的目录需要位于类路径中。 By default, the classpath is configured to basically be '.', as in, the current directory.默认情况下,类路径基本上配置为“.”,如在当前目录中。 If you messed with it, well, you broke that.如果你搞砸了,那么,你打破了它。 You shouldn't mess with that environment variable.你不应该弄乱那个环境变量。

The fix is to specify classpath manually every time you invoke java, or, use build systems that take care of this for you:修复方法是每次调用 java 时手动指定类路径,或者使用为您处理此问题的构建系统:

java -cp . A

will work fine, as long as you're in the directory containing A.class.只要您位于包含 A.class 的目录中,就可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM