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开发者_如何学Python:\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");
}
}
You need to set the classpath. See for example this SO question.
You shouldn't be using extdirs when invoking java, you should be setting your classpath with -cp
By the way, when invoking a main java class, you should provide the class name, not the path to the class, hence, it's likely mycompany.test (if your class that contains main is named test), not mycompany/test. It's not an error as Java fixes it for you.
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.
Try this to compile:
mkdir classes
javac -d classes *.java
Only create the /classes directory the first time. The -d directory tells javac to put your .class file under /classes.
To run, do this:
java -cp .;classes MyCompany.Test
This should work fine.
精彩评论