Search code examples
javapackagingjavac

Problems running java classfile from the folder


I have three source files in a folder. I simply want to compile them using commandline and then execute them. However, I'm having the following issue. I am on a windows box:

Code compiles fine:

C:\mycode\src\code>javac Source1.java Source2.java Source3.java

Does not run from the folder where class files are:

C:\mycode\src\deckofcards>java Source1
Exception in thread "main" java.lang.NoClassDefFoundError: Source1 (wrong name: code/Source1)
        at java.lang.ClassLoader.defineClass1(Native Method)
        at java.lang.ClassLoader.defineClassCond(Unknown Source)
        at java.lang.ClassLoader.defineClass(Unknown Source)
        at java.security.SecureClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.defineClass(Unknown Source)
        at java.net.URLClassLoader.access$000(Unknown Source)
        at java.net.URLClassLoader$1.run(Unknown Source)
        at java.security.AccessController.doPrivileged(Native Method)
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: Source1.  Program will exit.

However, it does run when moving to parent folder:

C:\mycode\src\code>cd ..

C:\mycode\src>java code/Source1
Hello1
Hello2
Hello3...
......
....

I want to distribute this source to someone and I'm not sure whether they will be on windows or unix box.

Eventually I want to create an executable jar file but that also was giving me an error like this.


Solution

  • Problem here is not with running Java files, it runs fine. So you wanted to understand the following:

    In order to run a Java program you need to do the following steps:

    1. Create Java source files (*.java files)
    2. Compile using javac to binary class files (*.class files)
    3. Run the class files using java executable

    We use package structure to keep organize the java files. In your case it is a simple application (and you use the package named "code"), but in a large production application we need to organize our code into many packages.

    While running the class file, we need to give the class file path (which includes the package path). So in your case you need to execute java code/Source1 to run your class.

    You can learn more from this link: http://docs.oracle.com/javase/tutorial/getStarted/cupojava/win32.html

    For creating a JAR file you can refer the link: http://docs.oracle.com/javase/tutorial/deployment/jar/build.html

    For making a JAR file executable ensure you add manifest file with main-class attribute.