I have been mostly using eclipse so far. Now I'm trying to run java from terminal but I have a problem with packages.
This is my Main.java
file:
package main;
class Main {
public static void main(String[] args) {
System.out.println("it's working");
}
}
I compile this using javac Main.java
and then run with java Main
which gives me:
java Main
Exception in thread "main" java.lang.NoClassDefFoundError: Main
Caused by: java.lang.ClassNotFoundException: Main
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
Could not find the main class: Main. Program will exit.
When I remove package Main
everything works fine. What am I missing?
java -version
gives:
java version "1.6.0_24"
OpenJDK Runtime Environment (IcedTea6 1.11.4) (6b24-1.11.4-1ubuntu0.12.04.1)
OpenJDK 64-Bit Server VM (build 20.0-b12, mixed mode)
You need to run the java command up one directory level and give it in the fully qualified package name, eg: java main.Main
See How the Java Launcher Finds User Classes to learn how this works.
You can use this command:
java main.Main
Make sure the main
(lowercase) package directory is on the classpath.
It is possible that your classpath is not set correctly. Since you gave your .java file a package it is unnamed no longer.
An example:
java -cp ./package1/ main.Main //from the current directory and
//if main package is contained in package1
You need to fully qualify the class name. For future reference if you want to run from the command line you must stop the indirection (for lack of a better term) at the package level. Say your class was in the package package1.package2.Main.java I would run it like so java -cp /blah/blah package1.package2.Main
Windows:
javac main\\Main.java
Mac:
javac main/Main.java
java main.Main
If you add package Main
, then you must put your source file in folder Main/Main.java. After that you can compile. When you run the program, go to Main folder using "cd", then write java -cp Main.Main
See my question similiar to yours noclassdeffounderror
try this...
In window , you just compile the code as
javac - d . Main.java
then a package(folder) with the name you specified in your class is created (in your code, package with name "main" is created) in the same path where your program reside...
Then you just run the program as java main.Main or java main/Main
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.