Search code examples
javapackagejavac

How do I compile my Java source files?


My source files are in this folder: c:\data\mycompany. All of my source files contain the following as the first line: package mycompany; Now from the c:\data folder, I compiled everything using this command: javac mycompany/*.java -extdirs c:\some\other\folder\with\libs. This compiles fine. Now when I try to execute it (again from c:\data) using this command: java mycompany/test then i get this error:

Exception in thread "main"
java.lang.NoClassDefFoundError:
mycompany/test Caused by:
java.lang.ClassNotFoundException:
mycompany.test at java.net.URLClassLoader$1.run(Unknown Source)

I also tried the below command but it reproduces the same error:

java mycompany/test -extdirs c:\some\other\folder\with\libs

Is this the proper way to compile/run?

Here is my source-code:

package MyCompany;

public class Test
{
  public static void main(String[] args) 
  {
    System.out.println("test");
  } 
}

Solution

  • that is saying that the .class files are not on the classpath how you are compiling should be fine, you need to add the directory with the resulting .class files to your classpath when you try and run your test code.

    java -cp <path to classes> classtorun
    

    so your example might look like

    java -cp <path to classes>;<path to libs> mycompany.Test
    

    you should really look at ANT to automate your compile and build to an executable .jar file. Nobody does this fiddly stuff by hand because of all the repetitive typing and chances for errors. ANT was created to avoid all this minutia and let you concentrate on solving coding problems and not struggling with the command line tools. Read this.