Creating an executable jar - java

I had written a program:
public class SystemShutdown {
public static void main(String[] args) {
try{
for(int i=0;i<10;i++){
Thread.sleep(1000);
}
Process p=Runtime.getRuntime().exec("shutdown -s -t 2700");
}catch(Exception e){}
}
}
I'd compiled and kept the .class file separate.
Now, I'd write a manifest file as:
Manifest-Version: 1.0
Main-Class: SystemShutdown
And saved with the name MANIFEST.MF
I'd put both (the .class file and the MANIFEST.MF file) in same directory.
Now I want to create an Executable Jar file. For that I'd done:
jar cvfm MyJar.jar *.*
A jar file is created after that.
But when I tries to execute it displays a message Java Exception occured.
Can anybody help me out?
I want to execute this program on the users double click.
Beside of the above scratch can anybody tell me the exact steps to be followed to create an executable jar?
I'm using Windows7 32bit and jdk7

The m option of the command line for jar says you'll provide the manifest file as the following parameter (in this case, after the jar file itself). So I suspect you want:
jar cvfm MyJar.jar MANIFEST.MF SystemShutdown.class
See the jar tool documentation for more details.
EDIT: I've just tried this and it works fine. Code:
// In Test.java
public class Test {
public static void main(String[] args) {
System.out.println("Hello");
}
}
// Manifest in MANIFEST.MF:
Manifest-Version: 1.0
Main-Class: Test
Command line and output:
javac Test.java
jar cvfm test.jar MANIFEST.MF Test.class
java -jar test.jar
Hello
Note that if you don't have a line terminator at the end of the Main-Class line in the manifest, that will cause an error, but it's somewhat better specified:
Failed to load Main-Class manifest attribute from test.jar

Related

What is the proper entry point, when compiling java to jar?

So, when I write my java file:
public class Program
{
public static void main(String[] args)
{
System.out.println("Serious business logic.");
}
}
Then in windows cmd, I compile this way:
javac Program.java
jar cfe Program.jar Program Program.class
java -jar Program.jar
It's fine, and the result is:
"Serious business logic."
When in Netbeans I create a Project, it adds this line:
package program;
And I can not compile in cmd, only inside the IDE.
I've tried manifest.txt, UTF8 encoding without BOM, plus linebreak at the and of file.
Manifest.txt:
Main-Class: program.Program
"jar cvfm Program.jar Manifest.txt Program.class"
and without manifest.txt, just in cmd program.Program
"jar cfe Program.jar program.Program Program.class"
When I tried to run:
java -jar Program.jar
it results in:
"Error: Could not find or load main class program.Program"
I've already checked the following websites:
http://www.skylit.com/javamethods/faqs/createjar.html
https://docs.oracle.com/javase/tutorial/deployment/jar/build.html
and haven't got any idea how to do. Could you please help me?
How do I compile with package keyword? What is the proper entry point?
Thanks!
(ps jre1.8.0_91 ; jdk1.8.0_66 should I use same 32 or 64 bit for both of jre and jdk?)
Make sure when you are compiling your program as a JAR, Program.class is inside of a folder called program. The package keyword that Netbeans has added at the beginning of your script is telling the executable that it is inside of a folder called program. If you are just adding the class file without making sure it is in the correct package (folder), it will not run properly because it does not know where to find it. Your command should be changed to:
jar cvfm Program.jar Manifest.txt program
where program is a folder containing Program.class. Your manifest may be left alone but also needs to be included with compilation.

Run a class in a sub package in a jar file on Windows command line

I exported a jar file from eclipse and in the jar file are various packages and sub packages with java class files.
I'd like to run one of these nested class files on the command line in Windows.
The class has a main and I am using the following to try to run it,
java -classpath .;./example.jar example
Note that example is the name of the class as well as the jar.
I've also tried to spell out the full path of the class
java -classpath .;./example.jar the.whole.path.example
How can I run the example class?
EDIT:
OK this is kind of stupid, the full path was incorrect. I checked this over numerous times yet it was only when I came back to it that I noticed the error.
Just running java -cp example.jar the.whole.path.example should do the trick. If not, then something with your JAR file is wrong. The class name must be fully qualified (with package name) and the specified class must have a correct main method:
public static void main(String[] args) {
}
Without seeing any of your code or any output (hint, hint) it's hard to say what's happening, but this works for me:
$ cat x/y/z/A.java
package x.y.z;
public class A
{
public static void main(String args[]) throws Exception
{
System.out.println("here in A");
}
}
$ javac x/y/z/A.java
$ jar cvf a.jar x/y/z/A.class
added manifest
adding: x/y/z/A.class(in = 459) (out= 311)(deflated 32%)
$ java -classpath a.jar x.y.z.A
here in A
And in case the poster or someone reading this in the future isn't familiar with Unix, the lines starting with $ are commands I type into the shell and everything else is output from those commands. Eclipse will take care of the first three for you, then the final java -classpath a.jar x.y.z.A is the command to execute the main method in the x.y.z.A class.
Check if your assumptions are correct. Show the structure of your jar and compare it to what you try to run:
jar tf example.jar
If the jar contains a lot of entries you might want to grep / find the relevant class:
jar tf example.jar | find /i "Example"

Java running external jar without IDE?

I've written a java program that reads an excel file with jxl.jar. It's currently working, but I have to use cmd to run the program. Double clicking the jar file does not appear to be working. These are the commands I use to compile and run the code:
javac -classpath C:/workspace/jxl.jar:. main.java GUi.java
jar cvfm run.jar manifest.txt Main.class GUI.class GUI$1.class GUI$2.class GUI$3.class Main$1MyCustomTableCellRenderer.class Main$1YourTableCellRenderer.class Main$MyCustomTableCellRenderer.class
java -cp run.jar Main
I'm not really sure why it's any different from double clicking it. I've compiled the jxl file into the run.jar file so I don't understand why it doesn't work?
An Example directly from Java Tutorial on Adding Classes to the JAR File's Classpath as suggested by #MadProgrammer in his comment.
We want to load classes in MyUtils.jar into the class path for use in MyJar.jar. These two JAR files are in the same directory.
We first create a text file named Manifest.txt with the following contents:
Class-Path: MyUtils.jar
Warning: 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.
We then create a JAR file named MyJar.jar by entering the following command:
jar cfm MyJar.jar Manifest.txt MyPackage/*.class
This creates the JAR file with a manifest with the following contents:
Manifest-Version: 1.0
Class-Path: MyUtils.jar
Created-By: 1.7.0_06 (Oracle Corporation)
The classes in MyUtils.jar are now loaded into the class path when you run MyJar.jar.
Read more...
Try this in command prompt:
Run the below command if you bundled the jar with all libraries
java -jar MyJar.jar
If you need to add jars at the time of execution please add all the jars at command line, as follows;
java -cp /path/jxl.jar;myJar.jar Class-Name-Main

JAR file not Running Properly

I have created a runnable jar file that contains the following classes:
Main.class (This contains the main method)
Form.class
WrapLayout.class
The manifest file (Manifest.txt) contains the following:
Main-Class: Main
(It has a new line at the end)
I have created the jar file using this command:
jar cfm Organizer.jar Manifest.txt Main.class Form.class WrapLayout.class
The jar file is created, but when I run it, the command window opens up for a split second, closes, and nothing else happens. The file is a swing application, and I am running Windows XP on Parallels Desktop for Mac, but I don't think that matters. Does anyone know what's wrong?
EDIT: I tried running the jar file in mac, and I got this error message in the console:
Exception in thread "main"
java.lang.UnsupportedClassVerionError: Main : Unsupported major.minor version51.0
follow these steps an test:
Start Command Prompt. Navigate to the folder that holds your class
files: C:>cd \mywork
Set path to include JDK’s bin. For example: C:\mywork> path
c:\Program Files\Java\jdk1.5.0_09\bin;%path%
Compile your class(es): C:\mywork> javac *.java
Create a manifest file: C:\mywork> echo Main-Class: YourMainClass >manifest.txt
Create a jar file: C:\mywork> jar cvfm YourMainClass.jar manifest.txt
*.class
Test your jar: C:\mywork> YourMainClass.jar

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