I am having two problems regarding compiling and running an Eclipse java project from command line. This works fine when I am just running from the eclipse IDE. I tried googling but couldn't really get the thing working. Any help is much appreciated.
Problem 1: When I try to compile from a location different from the directory where the .java file is, it throws the error "cannot read: myfile.java". But if I migrate to this directory then it compiles.
The command that I was giving is (when in some other directory):
javac -cp C:\ABC\src\XYZ myfile.java
The command that I was giving when in XYZ directory:
javac myfile.java
This generated two .class files myfile.class and Testing_Thread.class(I guess this because I have a thread in my code)
Problem 2: After I have compiled by going to its directory, when I try to run the program, I get the error "Exception in thread "main" java.lang.NoClassDefFoundError: myfile (wrong name: XYZ/myfile.java)" even when I am trying to run from the XYZ directory. I get the same error when I try to run from some other place also.
The command that I was giving when in XYZ directory:
java myfile
The command that I was giving when in some other place:
java -cp C:\ABC\src\XYZ myfile
I am also attaching a hierarchy of my directory structure if it is of any help:
These examples assume the following source structure:
Where D.java is:
The first problem, cannot read: myfile.java, is because it is not correct to use the
cp
command line option to point to your source code.This should instead be the following, where
javac
is run from your source folder, and we can use relative paths to the source files (NOTE -javac
is run from the source folder here):Or this, where we specify full paths to the source files, and
javac
can be run from anywhere (NOTE -javac
is run fromC:\
here):Both of the above options will result in your class files being created in the same folder as the source. I.e.:
For the second problem, if you try and run a class that has a package name from 'inside' the package, this will result in the name being wrong (NOTE -
java
being run from 'inside' the package here):To run the
D
class, you should be at the package 'root', and supply the Fully Qualified Class Name. I.e.:Note I get an exception as the
D
class doesn't have a main method, and so cannot be run. To fix, we add a main method:and re-run: