I ahve tried several approaches as on How do I run a Java program from the command line on Windows? and create exactly the same class and packages to use the same things.
Here is the sample class located on C:\SimpleJavaProject\src\com\hello\programs:
package com.hello.programs;
public class ABC {
public static void main(String[] args) {
System.out.println("Hello world");
}
}
Then I compile it in the usual way:
C:\SimpleJavaProject\src\com\hello\programs > javac ABC.java
Later, run it by giving the package name and then my java class name:
C:\SimpleJavaProject\src > java com.hello.programs.ABC
In each time I try to run java app, I get "Error: Could not find or load main class com.hello.programs.ABC" error. Then have a look at What does “Could not find or load main class” mean? page and tried some approaches on that page. But still the same error.
It is too simple, but still I have not managed to run the simple app yet. So, how to fix this problem? And after running the app, how can I pass args on cmd?
Update: I could already generate ABC.class file by running the following command. BUT, I cannot run the app and see the "Hello world" on the console.
cd C:\SimpleJavaProject\src\com\hello\programs
javac ABC.java
--> generates ABC.class in C:\SimpleJavaProject\src\com\hello\programs
java com.hello.programs.ABC
When you run this, java is going to check each and every CLASSPATH path for that + /com/hello/programs/ABC.class, will load that, and then run it.
This must mean that either:
[A] Your classpath does not include the current directory; The fix is java -cp . com.hello.programs.ABC.
[B] you didn't do what you wrote, and e.g. dir com/hello/programs.ABC.class prints nothing.
Note that you're not doing it right; a class file should never be in a directory path that includes src. If you don't want to bother with build tools like maven or gradle, I strongly suggest you don't bother with a src dir then either. If you must, the -d option can be passed to javac to tell it where tou put the file. If you want to separate source and class files, then that should be targeting a directory named bin or build or whatnot (a sibling of the src dir).
When you use javac ABC.java you are compiling the class, and javac places it in the current directory.
So java com.hello.programs.ABC would not work (because com/hello/programs/ABC.class file does not exists).
You can use the javac -d flag:
-d <directory> Specify where to place generated class files
For instance:
> javac -d . ABC.java
> java com.hello.programs.ABC
Hello world
> cd com\hello\programs
> dir
ABC.class
Would work, because javac did place ABC in com/hello/programs.
Update: For clarity, once you compiled using javac -d . ABC.java you can run it using java com.hello.programs.ABC and you should see Hello world in the screen.
Related
At the moment I am looking for another way to run my Java program from command line, other than adding it to a JAR file. My program has the following number of classes:
The name of the program file - MyProgram
Main class - Server1
second class - Client Handler
Package name - Items
3rd class - User1
4th class - User2
The main class and client handler alongside the package will have to run first in order for user 1 & user 2 to run, because they are client classes and are dependent on the main class.
javac *.java // compliles all java files in the dir
java MyClass // runs the particular file
If one class is dependent on another class that hasn't been compiled yet, the program won't run. So you should compile all files before trying to run the program dependent on other files.
If your files are packaged, then something like this
javac com.mypackage/.*java
java com.mypackage.MyClass
you must ensure that you add the location of your .class file to your classpath. So, if its in the current folder then add . to your classpath. Note that the windows classpath separator is a semi-colon ie ;
javac -cp . PackageName/*.java
java -cp . PackageName/ClassName_Having_main
Example. Suppose you have the following
Package Named: com.test
Class Name: Hello (Having main)
Java file is located inside "src/com/test/Hello.java"
then, from outside directory:
$ cd src
$ javac -cp . com/test/*.java
$ java -cp . com/test/Hello
Note that you can add -d to specify output directory of your class files whenever compiling
$ javac -d output_directory -cp . com/test/Hello
In windows the same thing will be working too, I already tried
Check out this from Oracle official site
Once you compile your code, you then run this from the top level:
java -cp . com.myprogram.MyProgram
That order thing you describe doesn't matter. They all get compiled together, and MyProgram will reference Server1, etc.
It may be more then you want to tackle right now but you might want to consider a build system like Maven. To start try out; How do I make my first Maven project?
You can use it to predefine the build order and if you want have it create a jar for you (or not).
Sounds like you will just need to open multiple command prompts and compile and run them in the order you need them to run. Let me know if I misunderstood question.
TO EXECUTE TWO JAVA PROGRAMS WHICH DEPENDS TO EACH OTHER.
(for example:two files Complex.java and Solution.java, where Soultion.java depends upon Complex.java.
So Complex.java should be compiled first and then the class file of Complex must be linked with Solution.java and then Solution.class must be executed for Output.)
REFER THE IMAGE WITH SYNTAX.
STEP 1:
COMPILE Complex.java
compiling Complex.java
syntax-
javac -d [path_where_class_File_build] [path_of_the_file\filename.java]
(Solution.java and Complex.java are Linked. ie-Solution.java calls Complex.java)
STEP 2:
COMPILE Solution.java
compiling Solution.java with linking Complex.class
with linking Complex.class(above created in step 1)
syntax-
javac -d [path_where_class_File_build] -cp [path_of_the_first_class_created] [path_of_the_file\filename.java]]
STEP 3:
EXECUTE THE Solution.class
java -cp [path_of_second_class_created] [class_Name]
(created in Step 3)
Directory path:
c:\home\test\src\com\bsoft\conc
I have my java program in src folder and I have my class file in conc folder.
I need to run my java program from home folder.When I run I'm getting error:
could not find or load main class
Set your class path for this java file:
java -cp C:\hello\build\classes com.javahowto.test.HelloWorld
or using Environment variables and run it from any third location from that machine.
It's time for you to read on about classpath ( a way to tell java compiler where to look for the class file you intend to run ).
Basically there are two ways to set classpath
a environment variable CLASSPATH having ':' separate directories in unix and ';' separated directories in windows
-classpath or -cp command line arg to javac command
Refer and read the below links completely
http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html
In my program com.bsoft.conc is a package name where my class file for the compiled program will be stored.If I have to run that from home folder we have to specify
java -classpath test\src com.bsoft.conc."class-file-name"
This is because we need to tell the JVM where it has to look for class file.
so , we have to specify navigation to the src using "test\src" and then
class file location "com.bsoft.conc.class-file-name"
If you have set environment variable in advanced settings then it will also be overriden if you specify classpath in cmd
I had a similar problem where I was trying to run a Java program that calls a method in a class that is in another directory. I read this page and added the directory to my classpath, but I made the mistake of using '~' which in Bash means '/home/user/'.
So this command did NOT work
java -classpath ~/CurrentDirectory:OtherDirectory program
But this command did
java -classpath /home/user/CurrentDirectory:OtherDirectory program
The answers here don't touch on the spaces problem.
If your path has spaces, you must wrap it inside the quotes, otherwise an error would show up:
C:
Program Files
MyProject
src
testpackage
Test.java
target
classes
testpackage
Test.class
package testpackage;
public class Test {
public static void main(String[] args) {
System.out.println("Test");
}
}
java -cp "C:\Program Files\MyProject\target\classes" testpackage.Test
In Linux ( Simple scenario with out consider them as packages )
> parent
|
|- stdlib
| |
| -Library.java
|- Main.java
COMPILE FROM PARENT > javac -cp ./stdlib: Main.java
RUN FROM PARENT > java -cp ./stdlib: Main
This question already has answers here:
What does "Could not find or load main class" mean?
(61 answers)
Closed 2 years ago.
I am running a simple "HelloWorld" Program. I get this error in the command prompt:
Could not find or load main class HelloWorld.
I have set the CLASSPATH and PATH variable in the system. In the cmd prompt, I am running from the directory where I have saved HelloWorld program. I can see the class name and the file name are same and also .class file created in the same directory. What else could be the problem?
My sample program looks like this:
package org.tij.exercises;
public class HelloWorld {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello World!!");
}
}
When the Main class is inside a package then you need to run it as follows :
java <packageName>.<MainClassName>
In your case you should run the program as follows :
java org.tij.exercises.HelloWorld
What's your CLASSPATH value?
It may look like this:
.;%JAVA_HOME%\lib\dt.jar;%JAVA_HOME%\lib\tools.jar
I guess your value does not contain this .;.
So, ADD IT .
When you done , restart CMD
That may works.
For example the file HelloWorld.java is in path: D:\myjavatest\org\yz\test and its package is: org.yz.test.
Now, you're in path D:\myjavatest\ on the CMD line.
Type this to compile it:
javac org/yz/test/HelloWorld.java
Then, type this to run it:
java org.yz.test.HelloWorld
You may get what you want.
I removed bin from the CLASSPATH. I found out that I was executing the java command from the directory where the HelloWorld.java is located, i.e.:
C:\Users\xyz\Documents\Java\javastudy\src\org\tij\exercises>java HelloWorld
So I moved back to the main directory and executed:
java org.tij.exercises.HelloWorld
and it worked, i.e.:
C:\Users\xyz\Documents\Java\javastudy\src>java org.tij.exercises.HelloWorld
Hello World!!
Since you're running it from command prompt, you need to make sure your classpath is correct. If you set it already, you need to restart your terminal to re-load your system variables.
If -classpath and -cp are not used and CLASSPATH is not set, the current directory is used (.), however when running .class files, you need to be in the folder which consist Java package name folders.
So having the .class file in ./target/classes/com/foo/app/App.class, you've the following possibilities:
java -cp target/classes com.foo.app.App
CLASSPATH=target/classes java com.foo.app.App
cd target/classes && java com.foo.app.App
You can check your classpath, by printing CLASSPATH variable:
Linux: echo $CLASSPATH
Windows: echo %CLASSPATH%
which has entries separated by :.
See also: How do I run Java .class files?
I had the same problem, mine was a little different though I did not have a package name. My problem was the Class Path for example:
C:\Java Example>java -cp . HelloWorld
The -cp option for Java and from what I can tell from my experience (not much) but I encountered the error about 20 times trying different methods and until I declared the class Path I was receiving the same error. Vishrant was correct in stating that . represents current directory.
If you need more information about the java options enter java -? or java -help I think the options are not optional.
I just did some more research I found a website that goes into detail about CLASSPATH. The CLASSPATH must be set as an environment variable; to the current directory <.>. You can set it from the command line in windows:
// Set CLASSPATH to the current directory '.'
prompt> set CLASSPATH=.
When you add a new environment setting you need to reboot before enabling the variable. But from the command prompt you can set it. It also can be set like I mentioned at the beginning. For more info, and if your using a different OS, check: Environment Variables.
One reason for this error might be
Could not find or load main class <class name>
Maybe you use your class name as different name and save the class name with another name you can save a java source file name by another name than class name. For example:
class A{
public static void main(String args[]) {
System.out.println("Hello world");
}
}
you can save as Hello.java but,
To Compile : javac Hello.java
This will auto generate A.class file at same location.
Now To Run : java A
Execute your Java program using java -d . HelloWorld command.
This command works when you have declared package.
. represent current directory/.
I had a similar problem when running java on win10
instead of
$ java ./hello
Error: Could not find or load main class ..hello
Run
$ java hello
Hello, World
I was getting the exact same error for forgetting to remove the .class extension when running the JAVA class. So instead of this:
java myClass.class
One should do this:
java myClass
I used IntelliJ to create my .jar, which included some unpacked jars from my libraries. One of these other jars had some signed stuff in the MANIFEST which prevented the .jar from being loaded. No warnings, or anything, just didn't work. Could not find or load main class
Removing the unpacked jar which contained the manifest fixed it.
I faced the same problem and tried everything mentioned here.
The thing was I didn't refresh my project in eclipse after class creation .
And once I refreshed it things worked as expected.
faced the same problem. solved by following these steps
go to directory containing the package 'org.tij.exercises' (e.g: in eclipse it may be your src folder)
use java org.tij.exercises.HelloWorld
For a lot of us, at least for me, I think the class path hierarchy is not intuitive since I'm working inside a directory structure and it feels like that ought to be it.
Java is looking at the name of the class based on it's package path, not just the file path.
It doesn't matter if:
i'm in the local directory ./packagefoo/MainClass, or
a directory up ./packagefoo/, or
one down ./packagefoo/MainClass/foo.
The command "java packagefoo.MainClass" is running off the root %CLASSPATH% which means something significant to Java. Then from there it traverses package names, not path names like us lay coders would expect.
So if my CLASSPATH is set to %CWD%/, then "java packagefoo.MainClass" will work.
If I set the CLASSPATH to %CWD%/packagefoo/ then packagefoo.MainClass can't be found.
Always "java MainClass" means nothing, if it is a member of "package", until I rip out the java code "package packagefoo;" and move the Class File up a directory.
In fact if I change "package packagefoo;" to "package foopackage;" I have to create a subfolder under CLASSPATH/foopackage or foopackage.MainClass stops working again.
To make matters worse, Between PATH, CLASSPATH, JAVAHOME, for Windows, JDeveloper, Oracle Database, and every user name it was installed under, I think a coder trying to just get something up fast ends up brute forcing path variables and structure until something works without understanding what it means.
at least i did.
Create a folder org/tij/exercises and then move HelloWorld.java file. Then run below command
javac -cp . org/tij/exercises/HelloWorld.java
AND
java -cp . org/tij/exercises/HelloWorld
I was facing similar issue but it was due to space character in my file directory where I kept my java class.
Scenario given below along with solution:
public class Sample{
public static void main(String[] args) {
System.out.println("Hello world, Java");
}
}
My Sample.java class was kept at Dir "D:\Java Programs\Sample.java"[NOTE: Package statement not present in java class].
In command prompt, changed directory to "D:\Java Programs\", my programmed compiled but failed to run with error "Could not find or load main class"
After all the possible solutions over SOF(nothing worked), I realized may b space causing me this issue.
Surprisingly removal of folder name space char['Java Programs' -> 'JavaPrograms'], my program executed successfully. Hope it helps
I created a Java project to call a Web service.
It has one Main java file and another class file.
I have used some jar files for HTTP client.
In Eclipse it runs fine.
I need to run the Java program in command prompt by passing some arguments.
In command prompt I went to src folder containing main java and sub class java file and gave the following command
javac mainjava.java
I'm getting following error
mainjava.java:14: cannot find symbol
symbol : class SubClass
here SubClass is my another java class file used to call the web service.
How to run the program by passing arguments?
javac is the Java compiler. java is the JVM and what you use to execute a Java program. You do not execute .java files, they are just source files.
Presumably there is .jar somewhere (or a directory containing .class files) that is the product of building it in Eclipse:
java/src/com/mypackage/Main.java
java/classes/com/mypackage/Main.class
java/lib/mypackage.jar
From directory java execute:
java -cp lib/mypackage.jar Main arg1 arg2
A very general command prompt how to for java is
javac mainjava.java
java mainjava
You'll very often see people doing
javac *.java
java mainjava
As for the subclass problem that's probably occurring because a path is missing from your class path, the -c flag I believe is used to set that.
You can use javac *.java command to compile all you java sources. Also you should learn a little about classpath because it seems that you should set appropriate classpath for succesful compilation (because your IDE use some libraries for building WebService clients). Also I can recommend you to check wich command your IDE use to build your project.
All you need to do is:
Build the mainjava class using the class path if any (optional)
javac *.java [ -cp "wb.jar;"]
Create Manifest.txt file with content is:
Main-Class: mainjava
Package the jar file for mainjava class
jar cfm mainjava.jar Manifest.txt *.class
Then you can run this .jar file from cmd with class path (optional) and put arguments for it.
java [-cp "wb.jar;"] mainjava arg0 arg1
HTH.
javac only compiles the code. You need to use java command to run the code. The error is because your classpath doesn't contain the class Subclass iwhen you tried to compile it. you need to add them with the -cp variable in javac command
java -cp classpath-entries mainjava arg1 arg2 should run your code with 2 arguments
so I am having a noob moment here, I haven't ever used the command line to run a java program before but I need to right now. The problem I am having is that when I try to run the program I get a ClassNotFoundException. My class is called OmadUpdate. I already have compiled the OmadUpdate.java file into OmadUpdate.class using the javac command. I have checked the directory and they are both definitely there, however when I run the java OmadUpdate command, it gives me an error message saying
Exception in thread "main" java.lang.NoClassDefFoundError: OmadUpdate (wrong name: org/openmetadata/main/OmadUpdate)
......
......
Could not find the main class: OmadUpdate. Program will exit
But its right there in the directory. When I type dir I have both OmadUpdate.class and OmadUpdate.java. I have even tried using "java org.openmetadata.main.OmadUpdate" because that is the package name that it is under. I am stumped. Thanks for the assistance.
Your class appears to have been declared in the org.openmetadata.main package.
To get java to load the class correctly, it needs to be in the correct directory structure that matches the package structure.
So the classfiles for org.openmetadata.main.OmadUpdate should be in the directory org\openmetadata\main.
Then, when you run the java command, the root of this directory structure should be on the classpath - for a simple example this just means that your current directory should be the parent directory of org\openmetadata\main.
When running java you need to specify the full classname using periods not slashes, i.e.
java org.openmetadata.main.OmadUpdate
After you compile the class with javac, you'll have the following directory structure:
org/
openmetadata/
main/
OmadUpdate.class
OmadUpdate.java
Make sure you're in the parent directory of org, then run
java -cp . org.openmetadata.main.OmadUpdate
Class names have their nested package names separated by periods, while the directories use slashes. Odds are good you tried java -cp . org/openmetadata/main/OmadUpdate when you should have (since you are specifying a class name) tried java -cp . org.openmetadata.main.OmadUpdate
Note that for this to work, you must run it in the directory just above the org subdirectory. Otherwise that classpath directive cp . will start the search in the wrong directory.
launch your java app with the classpath set:
java -cp . org.openmetadata.main.OmadUpdate
-cp . won't do anything I don't think. You have to make sure you are invoking java in the right directory, which is the part to the first package name / folder (in your case org)
You need to use the full package and class name to run it.