Using java.exe with .class file from Eclipse - java

I have a programming working in Eclipse. I need to be able to send the project to my instructor, who will run it from the command line with java.exe.
The program takes arguments, and I have tested those within Eclipse and they work fine, however, when I attempt to use java.exe to execute the main.class file that is in the bin folder of my project I get the following error:
Error: Could not find or load main class C:\Workspace\Sort\bin\Main.class
I have JRE 1.8.0_60 installed on my system and not the JDK. However, whatever Eclipse uses to compile, I should be able to use as well. I know I can export it as a JAR, but that is not part of the assignment and I don't think JAR files take arguments.
Any ideas?

Keep in mind that the default classpath for java.exe only includes the current working directory. So if you're not executing java from the bin/ folder of your project, it won't know where to find your class. You need to either run from C:\Workspace\Sort\bin or use the -cp option to include that folder on the classpath. For example:
java -cp C:\Workspace\Sort\bin Main arg1
Also note that you should not include the .class file extension when specifying the name of the class.

You can send parameters when executing a jar :
using arguments
cmd: java -jar Myapp.jar arg1 arg2
code:
public static void main(String[] args) {
//args[0] = arg1
//args[1] = arg2
}
using parameters:
cmd: java -Darg1_name=arg1 -Darg2_name=arg2 -jar Myapp.jar
code:
public static void main(String[] args) {
//System.getProperty("arg1_name") = arg1
//System.getProperty("arg2_name") = arg2
}

Related

Cannot run Java app on cmd using Java11 and Windows

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.

Java does not see JAR file in classpath

Not a JAVA Newbie!
I keep getting Error: Could not find or load main class, this was working last week. My Commandline is
java -cp sample.jar com.sample.Myclass
sample.jar exists in current folder, Myclass.class has public static void main(String[] args) method
I have tried
java -cp C:\fullPath\sample.jar com.sample.Myclass
When I add option -verbose:class to the command line above I see all jars in jre\lib but not classes from my sample.jar
Why is java ignoring my -cp /-classpath argument?
JAR file is generated as artifact from IntelliJ and Eclipse->Export JAR as well

How to build an executable program using eclipse, there are parameters for the program

How can I build an executable program written in java using eclipse? and there are arguments need to be passed in ubuntu terminal.
the main function is like this:
public class Sample {
public static void main(String[] args) {...}
and I would like to call it in terminal like this:
$./program args[1] args[2]
The answers to this question give a number of options for giving a java program an executable wrapper: How can I convert my Java program to an .exe file?
That said, my preference for use on linux tends to be just bundling my compiled classes as a jar (eclipse provides an export to jar tool) and writing a shell script like:
#!/bin/bash
export CLASSPATH=`dirname $0`/my-archive.jar
java -cp $CLASSPATH my.package.Sample $#
That sets the classpath relative to the location of the script (so you can call the script from anywhere) and passes any arguments given to the script along to the java program.

How to run Java program in command prompt

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

How to run a JAR file

I created a JAR file like this:
jar cf Predit.jar *.*
I ran this JAR file by double clicking on it (it didn't work). So I ran it from the DOS prompt like this:
java -jar Predit.jar
It raised "Failed to load main class" exceptions. So I extracted this JAR file:
jar -xf Predit.jar
and I ran the class file:
java Predit
It worked well. I do not know why the JAR file did not work. Please tell me the steps to run the JAR file
You need to specify a Main-Class in the jar file manifest.
Oracle's tutorial contains a complete demonstration, but here's another one from scratch. You need two files:
Test.java:
public class Test
{
public static void main(String[] args)
{
System.out.println("Hello world");
}
}
manifest.mf:
Manifest-version: 1.0
Main-Class: Test
Note that the text file must end with a new line or carriage return.
The last line will not be parsed properly if it does not end with a
new line or carriage return.
Then run:
javac Test.java
jar cfm test.jar manifest.mf Test.class
java -jar test.jar
Output:
Hello world
java -classpath Predit.jar your.package.name.MainClass
Before run the jar check Main-Class: classname is available or not in MANIFEST.MF file. MANIFEST.MF is present in jar.
java -jar filename.jar
You have to add a manifest to the jar, which tells the java runtime what the main class is.
Create a file 'Manifest.mf' with the following content:
Manifest-Version: 1.0
Main-Class: your.programs.MainClass
Change 'your.programs.MainClass' to your actual main class. Now put the file into the Jar-file, in a subfolder named 'META-INF'. You can use any ZIP-utility for that.
A very simple approach to create .class, .jar file.
Executing the jar file. No need to worry too much about manifest file. Make it simple and elgant.
Java sample Hello World Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Compiling the class file
javac HelloWorld.java
Creating the jar file
jar cvfe HelloWorld.jar HelloWorld HelloWorld.class
or
jar cvfe HelloWorld.jar HelloWorld *.class
Running the jar file
java -jar HelloWorld.jar
Or
java -cp HelloWorld.jar HelloWorld
If you don`t want to create a manifest just to run the jar file, you can reference the main-class directly from the command line when you run the jar file.
java -jar Predit.jar -classpath your.package.name.Test
This sets the which main-class to run in the jar file.
Java
class Hello{
public static void main(String [] args){
System.out.println("Hello Shahid");
}
}
manifest.mf
Manifest-version: 1.0
Main-Class: Hello
On command Line:
$ jar cfm HelloMss.jar manifest.mf Hello.class
$ java -jar HelloMss.jar
Output:
Hello Shahid
Eclipse Runnable JAR File
Create a Java Project – RunnableJAR
If any jar files are used then add them to project build path.
Select the class having main() while creating Runnable Jar file.
Main Class
public class RunnableMainClass {
public static void main(String[] args) throws InterruptedException {
System.out.println("Name : "+args[0]);
System.out.println(" ID : "+args[1]);
}
}
Run Jar file using java program (cmd) by supplying arguments and get the output and display in eclipse console.
public class RunJar {
static StringBuilder sb = new StringBuilder();
public static void main(String[] args) throws IOException {
String jarfile = "D:\\JarLocation\\myRunnable.jar";
String name = "Yash";
String id = "777";
try { // jarname arguments has to be saperated by spaces
Process process = Runtime.getRuntime().exec("cmd.exe start /C java -jar "+jarfile+" "+name+" "+id);
//.exec("cmd.exe /C start dir java -jar "+jarfile+" "+name+" "+id+" dir");
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream ()));
String line = null;
while ((line = br.readLine()) != null){
sb.append(line).append("\n");
}
System.out.println("Console OUTPUT : \n"+sb.toString());
process.destroy();
}catch (Exception e){
System.err.println(e.getMessage());
}
}
}
In Eclipse to find Short cuts:
Help ► Help Contents ► Java development user guide ► References ► Menus and Actions
I have this folder structure:
D:\JavaProjects\OlivePressApp\com\lynda\olivepress\Main.class
D:\JavaProjects\OlivePressApp\com\lynda\olivepress\press\OlivePress.class
D:\JavaProjects\OlivePressApp\com\lynda\olivepress\olives\Kalamata.class
D:\JavaProjects\OlivePressApp\com\lynda\olivepress\olives\Ligurian.class
D:\JavaProjects\OlivePressApp\com\lynda\olivepress\olives\Olive.class
Main.class is in package com.lynda.olivepress
There are two other packages:
com.lynda.olivepress.press
com.lynda.olivepress.olive
1) Create a file named "Manifest.txt" with Two Lines, First with Main-Class and a Second Empty Line.
Main-Class: com.lynda.olivepress.Main
D:\JavaProjects\OlivePressApp\ Manifest.txt
2) Create JAR with Manifest and Main-Class Entry Point
D:\JavaProjects\OlivePressApp>jar cfm OlivePressApp.jar Manifest.txt com/lynda/olivepress/Main.class com/lynda/olivepress/*
3) Run JAR
java -jar OlivePressApp.jar
Note: com/lynda/olivepress/* means including the other two packages mentioned above, before point 1)
If you don't want to deal with those details, you can also use the export jar assistants from Eclipse or NetBeans.
Follow this answer, if you've got a jar file, and you need to run it
See troubleshooting sections for hints to solve most common errors
Introduction
There are several ways to run java application:
java -jar myjar.jar - is the default option to run application
java -cp my-class-path my-main-class or java -classpath my-class-path my-main-class
java --module-path my-module-path --module my-module/my-main-class
Deployment to an enterprise server. It's when you have war or ear file. We'll omit the explanation for this
case
In this answer I'll explain, how to run a jar if you have to run it manually, give hints to resolve common problems.
java -jar
Start with the most common option: run the jar file using the -jar. Example:
java -jar myjar.jar
If it fails:
with no main manifest attribute, then the jar is not executable:
If you're trying to build a jar
see Can't execute jar- file: "no main manifest attribute"
Otherwise, proceed with classpath or module-path solution below
with other error, then see "Troubleshooting" section below
Classpath or module path
If -jar failed, then the jar should be run using classpath or module-path.
Module-path is used, when an application is modular itself.
JPMS - Java Platform Module System - is a modern way to develop, distribute and run applications. For details:
Watch excellent Modular Development with JDK 9 by Alex Buckley
See awesome-java-module-system
To run a jar:
Determine if it's modular or not:
Invoke:
jar --describe-module --file=path-to-jar-file
Examine output:
If you see No module descriptor found. in the first line, then proceed with classpath solution below
If you see something similar to:
org.diligentsnail.consoleconsumer#1.0-SNAPSHOT jar:file:///home/caco3/IdeaProjects/maven-multi-module-project-demo/jars/console-consumer.jar!/module-info.class
requires java.base mandated
requires org.diligensnail.hellolibrary
continue with module-path solution below
See also: List modules in jar file
Classpath
Try the following:
java -cp my-jar.jar my-main-class
-cp is the same as -classpath
my-jar.jar is the jar to run
my-main-class is name of the class with static void main(String[]) method
Example:
java -cp jars/console-consumer.jar org.diligentsnail.consoleconsumer.Main
Module-path
Try the following command:
java --module-path my-jar.jar --module my-module-name/my-main-class
my-jar.jar is the jar to run
my-module-name is name of the module where my-main-class belongs
Usually my-module-name is in the module-info.java file
my-main-class - the class with the static void main(String[]) method
If it fails with FindException:
Example of message:
Error occurred during initialization of boot layer
java.lang.module.FindException: Module javafx.fxml not found, required by org.diligentsnail.javafxconsumer
Usually, this means the my-jar.jar has a dependency on the other jar.
For example, the application uses a third party library.
See "Supplying dependencies" below
Troubleshooting
UnsupportedClassVersionError
Update java. See List of Java class file format major version numbers?
NoClassDefFoundError, NoSuchMethodError, NoSuchFieldError
See:
"Supplying dependencies" section
Why am I getting a NoClassDefFoundError in Java?
Supplying dependencies
An Error or Exception is thrown when an application run with missing or out of date dependencies.
Common exceptions and errors:
NoClassDefFoundError, NoSuchFieldError, NoSuchMethodError
ClassNotFoundException, NoSuchFieldException, NoSuchMethodException
FindException
To supply dependencies:
Determine the list of dependencies
Usually it's a list of jar or can be a list of directories or both
Join the list with : if you're running Unix, ; - if you're on Windows
Invoke java with -classpath or --module-path
Example
Project maven-multimodule-project-demo
I'm trying to run console-consumer.jar:
Command:
java -classpath jars/console-consumer.jar org.diligentsnail.consoleconsumer.Main
jars/console-consumer.jar is the jar I'm trying to run
org.diligentsnail.consoleconsumer.Main is the class with main method
Error I get:
Exception in thread "main" java.lang.NoClassDefFoundError: org/diligentsnail/hellolibrary/Hello
at org.diligentsnail.consoleconsumer.Main.main(Main.java:11)
Caused by: java.lang.ClassNotFoundException: org.diligentsnail.hellolibrary.Hello
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
... 1 more
Missing dependency is jars/hello-library.jar
Correct command:
java -classpath jars/console-consumer.jar:jars/hello-library.jar org.diligentsnail.consoleconsumer.Main
To run jar, first u have to create
executable jar
then
java -jar xyz.jar
command will work

Categories

Resources