I am trying to compile and run some java files I have made in Eclipse. The full path to the .java file is C:\Users\MYNAME\Documents\Java\Introduction\src\tests\Test.java
. tests
is the package I created in Eclipse and src
is a folder that Eclipse made under Introduction
(which is the project name).
In my environment variables, I have the following relevant variable:
JAVA_HOME
C:\Program Files (x86)\Java\jdk1.7.0_40\bin
Under system variables I have the following:
CLASSPATH
%JAVA_HOME%
I go to my cmd and cd
into the tests
directory (cd C:\Users\MYNAME\Documents\Java\Introduction\src\tests
). Then I compile using javac Test.java
. This seems to work as I then have a Test.class
file under the same directory. Now I want to run the file, I type java Test
and I get the error, "could not find or load main class". I've tried a variety of things including appending .class
and .java
to the end but I keep getting the error. I looked at some answers and docs and I managed to get it to work if I cd
into:
cd C:\Users\MYNAME\Documents\Java\Introduction\src
(i.e, get out of the package)
and then run:
java -cp . tests.Test
So that seems to temporarily set the class path to the current directory, and run Test from the package tests
. However, I want to simply be able to type java Test
. I know it's possible as I used to be able to do it, but now for some reason I cannot (I must have changed something along the way...).
Any help is appreciated.
However, I want to simply be able to type
java Test
That will only work if Test
is in the default package - it's as simple as that. You need to pass the java
executable the fully-qualified name of the class you want to launch. There's no way round that.
Of course, you could create your own launcher which looks in the current directory for class files, finds out the fully-qualified name of the classes within those files, and launches java
providing the full name and probably specifying an appropriate classpath... but that seems like a lot of hassle compared with just including the package name in the command.
See more on this question at Stackoverflow