Cannot run simple compiled java program?

2020-05-08 07:19发布

问题:

I am on Arch Linux, I just installed JRE and JDK and all the proper bin files (javac and java) are in /opt/java/bin/

I simply compiled a standard hello world, and compiled it with javac running javac ./hello.java and that made a class.

Now my problem is running it. I run java ./helloworld.class and it gives me an error, even if the file I point java to is non-existant:

Exception in thread "main" java.lang.NoClassDefFoundError: //helloworld/class
Caused by: java.lang.ClassNotFoundException: ..helloworld.class
(..omitted for clarity..)
Could not find the main class: ./helloworld.class.  Program will exit.

You will notice the first line of the error, it munges the path //helloworld/class

When I feed java an absolute path, i.e java /home/foo/helloworld.class it gives the same error, but replaces the path's / with . in the first line, again munged.

What do you think is wrong? I really don't know why it is doing this..

回答1:

When you run java, you just pass it the fully qualified class name (including package), not the file name.

java helloworld will look for helloworld.class.

java helloworld.class will look for helloworld/class.class



回答2:

You do not run a file as # java file.class you run it as # javac PATH/file.java # java PATH/file

Do not add .class while using JAVA command.



回答3:

Actually you should compile it like this

javac helloword.java

run the program

java helloword


回答4:

And yet another thing: add command line option "-classpath ." or it short version "-cp .", i.e. your command line should look like: java -cp . helloworld

this is if your class is in your current directory. Otherwise "." should be replaced by path where the class(es) may be found.