I want to run a Java project from the command line which I start using a batch file, but I get the wrong name error.
The directory setup:
- srcMVC
- bin (folder with .class files)
- src (folder with .java files)
- Batch file
Batch file:
set path=C:\Program Files\Java\jdk1.7.0_09\bin
javac src\model\*.java -d bin -cp src
javac src\controller\*.java -d bin -cp src
javac src\view\*.java -d bin -cp src
javac src\main\*.java -d bin -cp src
PAUSE
java bin\main.Main
PAUSE
Compiling works, but I get the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: bin\main/Main (wrong name: main/Main)
Any suggestions?
package main;
// omitted imports
public class Main {
// omitted variables
public static void main(String[] args) {
// omitted implementation
}
}
The following statement resolved my error:
NoClassDefFoundError
in Java comes when Java Virtual Machine is not able to find a particular class at runtime which was available during compile time.For example if we have a method call from a class or accessing any static member of a Class and that class is not available during run-time then JVM will throw
NoClassDefFoundError
.By default Java
CLASSPATH
points to current directory denoted by "." and it will look for any class only in current directory.So, You need to add other paths to
CLASSPATH
at run time. Read more Setting the classpathjava -cp bin main.Main
where
Main.class
containspublic static void main(String []arg)
Java run time (in your case the java.exe command), takes the class file name that containst the main() method as input. I guess you should be invoking it as "java bin\main" assuming there is a main.class which has a public static void main (String[]) method defined.
Note: General practice is to capitalize the first literal of any class name.
java bin/main.Main
is wrong, you must specify-cp
here:Here the first argument is the class name which should be found in the classpaths, rather than the class file location. And
-cp
just adds the logical path to classpaths. You should make the root of your project searchable in the classpath.and for those javac commands, you have already specified the correct path, so you don't need
-cp src
. The difference here is the javac command uses logical path for.java
files, while using java command you could only specify the path in-cp
attribute.You could also execute
java main.Main
without-cp
if you enter the directorybin
:Since the current path will be automatically be searched by java as a classpath.
Assuming you have a class called Main you have to run it with this command:
It will call your main method.
you are wrongly exicuting java bin\main.main
main() is your main method but you should supply java interpreter the
Class Name
which implements main()So if your class name is Test and file name is Test.java which has main() method
java Test
if your Test.java/Test class in is package my.test e.g -
package com.my.test;
than,
java com.my.test.Test
hope you got it !!