Create a java executable with Eclipse - java

This is a totally newbie question. I'm running Eclipse on Ubuntu. I created a test project that I want to compile to an executable (whataver the linux equivalent is of a Windows .exe file). Here's the contents of my program:
public class MyTest {
public static void main(String[] args) {
System.out.println("You passed in: " + args[0]);
}
}
I want to know how to compile it and then how to execute it from the command line.
Thanks!

You need to create an executable JAR file. Steps will follow shortly.
Right click on the project and select JAR file under Export.
Enter the path where you want it to be saved. The example here is of Windows. Change according to your platform.
Click Next.
Edit the Main Class field by browsing and selecting the location of your class that contains the main method.
Run it
To run the JAR file, open up a shell or command prompt and execute the following command:
java -jar path/to/test.jar

In Eclipse, choose file then export, and you will have to choose runnable jar. Also, you will be prompted to select the main class, MyTest in your case.

The Eclipes tutorials are very helpful, if you do the "create a Hello World application" tutorial it will walk you through the process of setup the project, building the app and running the jar file.

I want to know how to compile it ...
See other answers on how to get Eclipse to create a JAR file.
... and then how to execute it from the command line.
In the simple case, you execute it by running java -jar yourApp.jar <args>.
If your application depends on external libraries, then it is a bit more complicated ...
how come I would choose jar file over executable jar file?
Because a JAR file is portable, and a binary executable is not.
Because JIT compiled code runs faster than code that is compiled ahead of time.
Because the standard Java tool chain does not support creation of binary executables. Ditto for Eclipse, AFAIK.

Marked solution does not work.
Use "runnable" jar instead and then java -jar <jarfile>

Related

Java - Executable Jars

I wrote a Java GUI program in Netbeans IDE 8.0.1 called SampleChat and used the 'clean and build' function to create a jar file.
I went to the 'dist' directory that Netbeans created and double-clicked the jar file it produced.
A cmd window opened with the following line:
"Error: could not find or load main class.
However, when I opened cmd, changed to the same 'dist' directory and typed the command:
java -jar "SampleChat.jar"
the program ran just fine.
Can I not use Netbeans to create jar files that execute on double-click?
I did not use any pre-existing jar files to complete the program, hence, there was no 'lib' directory or anything like that.
I intend to share programs from a USB stick so it is vital that the only requirement is a JVM, mouse and maybe some fingers to double-click it.
An awkward solution I came up with is to write a batch file that runs the program, but it requires the jar file to not be moved around - screw that.
So how do I make my programs double-click executable?
I guess you are missing to create a manifest file. Therefore it's unknown what your mainclass is. In your java command executed from a terminal you defined the mainclass to execute.
From the tasks you mentioned I guess you are using gradle to build your jar?
Here http://www.gradle.org/docs/current/userguide/java_plugin.html in chapter 23.14.1
an example of an manifest is given.
If you add attributes 'Main-Class': 'com.project.MainClass' it should work.
BR

Jar not starting on double click, but starts from command line

I'm using IntelliJ to create JAR file, and it executes normally when run from command line, but on double clicking it, nothing happens. The JAR I export from eclipse work normally, and since I'm a beginner using IntelliJ my guess is that I am doing something wrong.
I'm exporting the JAR in this way:
Project structure -> jar -> from modules and dependencies then use this
configuration to build.
Not sure why everyone is playing dumb about self executing jars.
Just add a MANIFEST.MF file and specify the fully qualified main class as Main-Class: my.package.MyClass
Also, make sure your executable type for .jar file type is Java
Once you do this you can just double click the jar to execute it.
Intellij will not execute a JAR for you. Remember JAR is a container, Is the same as if you were asking to execute a ZIP file.
What I am sure you want is to execute a class inside your jar file. Which would be the class which has the:
public static void main(String[] args) { ... }
You have two options:
1) execute the jar from command Line
2) right click on the "main" word I wrote above and then press RUN.. You will see a small green arrow (play button). That is the only way of running a class inside Intellij.
Hope it helps
If your JAR starts from the command line using jar -jar <file>, that's as executable as a JAR file gets (in other words, metadata specifies where the main class is). You can if you want use the OS provided tools to specify that when you double click on a .jar file, it should execute java -jar <file>, but that's beyond the scope of JAR files. If you're running Windows for example, you should be able to achieve this by following the procedure outlined here. Again, this is OS specific and may even be specific to which version you're running, and is essentially just a fancy wrapper around the double-click event to execute the java -jar command.
Make sure that the x-flag is set for the jar.
java -jar xyz.jar
does not need that, but double click need it:
ls -l xyz.jar
chmod 755 xyz.jar

What will netbeans IDE do when I press Ctrl+F6 to run a java file?

I have no idea of how Netbeans IDE run a java file.
Firstly, it would ensure the .class file is up-to-date.
Then, execute the class. But from where (working directory) and with which command (parameter)?
I observe difference on how relative path is located when I run the java file from Netbeans IDE and when I run using Windows command prompt (i.e > java pack.age.name.ClassName)
You can find that out by putting this at the start of the main method of the class:
System.out.println(new File(".").getAbsolutePath());
It looks like it will run from the directory that the project is in (eg. ....\NetBeansProjects\JavaApplication1)
You cannot specify command line arguments for a single class (that I am aware of). To do that you have to use the Project | Properties (and there you can also set the working directory).
I would suggest that you do not write code that depends on the working directory if you can avoid it though...
You can get informative results by running the project's build.xml from the command line in verbose mode: ant -verbose run. Look for the [java] command options under run:. Typing ant -p will show you the available targets.

System.out not working when calling jar-file from Windows command line

I have this class:
public class Test {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
And I used Eclipse's "Export to runnable JAR" function to make it into a executable jar-file (test.jar). When I run this program in Eclipse, it prints out "Hello World!", but when I call the jar-file from the command line, nothing happens.
I have tried calling the jar-file like this:
test.jar
test.jar -jar
There is no output whatsoever.
I have another program that also has a side effect (in addition to output to stdout) and while the side effect is being performed (which tells me the jar-file was definitely executed), again no output is given to the command line. I have also tried using stderr, but that makes no difference. Does anybody know how I can make this work?
Thanks!
You must run the JAR using
java -jar test.jar
(Your JRE's bin folder must be added to PATH in order to get the command working from any location)
NOTE: I know you created the JAR using Eclipse but you might want to know how does an executable JAR works
The previous answers are correct, so I'll just clarify a bit the "executable jar" concept.
There's no such thing as an "executable jar", equivalent to an exe file in windows, in an "executable jar" you'll be only specifying the "entry" point ( your main class you want to be executed by default )
A jar is basically just an archive, you'll still need java to actually launch the jar ( java -jar your.jar )
The fact that in windows you might have an association with javaw.exe means this will be launched by the OS when you double-click on the jar, like a .txt file being opened automatically with notepad, it doesn't make the .txt an executable file.
Check this out as well :
JAR files revealed
When you invoke the jar using 'test.jar' the starting of the app is handed off to the registered java handler for jar files, which doesn't run in the context of the command line.
The default jar handler doesn't open console based System.{out,err} file handles, as it would mean a cmd style window for each of the jar files launched, which is not an ideal situation.
The previous answer, using java -jar test.jar causes it to run within the context of the current cmd window, and thus you will see the output.

How do I create executable Java program? [duplicate]

This question already has answers here:
How can I convert my Java program to an .exe file?
(16 answers)
Closed 8 years ago.
I have programmed a Java Program in JCreator, everything is done, but I want to create an executable file from it, ie I dont want to have to run the program by loading the java classes and compiling then executing, but instead have it as a stand alone executable file.
What the quickest way to do this?
You can use the jar tool bundled with the SDK and create an executable version of the program.
This is how it's done.
I'm posting the results from my command prompt because it's easier, but the same should apply when using JCreator.
First create your program:
$cat HelloWorldSwing.java
package start;
import javax.swing.*;
public class HelloWorldSwing {
public static void main(String[] args) {
//Create and set up the window.
JFrame frame = new JFrame("HelloWorldSwing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Hello World");
frame.add(label);
//Display the window.
frame.pack();
frame.setVisible(true);
}
}
class Dummy {
// just to have another thing to pack in the jar
}
Very simple, just displays a window with "Hello World"
Then compile it:
$javac -d . HelloWorldSwing.java
Two files were created inside the "start" folder Dummy.class and HelloWorldSwing.class.
$ls start/
Dummy.class HelloWorldSwing.class
Next step, create the jar file. Each jar file have a manifest file, where attributes related to the executable file are.
This is the content of my manifest file.
$cat manifest.mf
Main-class: start.HelloWorldSwing
Just describe what the main class is ( the one with the public static void main method )
Once the manifest is ready, the jar executable is invoked.
It has many options, here I'm using -c -m -f ( -c to create jar, -m to specify the manifest file , -f = the file should be named.. ) and the folder I want to jar.
$jar -cmf manifest.mf hello.jar start
This creates the .jar file on the system
You can later just double click on that file and it will run as expected.
To create the .jar file in JCreator you just have to use "Tools" menu, create jar, but I'm not sure how the manifest goes there.
Here's a video I've found about: Create a Jar File in Jcreator.
I think you may proceed with the other links posted in this thread once you're familiar with this ".jar" approach.
You can also use jnlp ( Java Network Launcher Protocol ) too.
If you are using Eclipse , you can try the below 7 steps to get a .exe file for Windows.
Now you have a JAR file. Use java -jar path/jarname.jar to execute.
If you want to convert this to .exe, you can try http://sourceforge.net/projects/launch4j/files/launch4j-3/
STEP7:
Give the .xml file an appropriate name and click "Save". The .xml file is standard, don't worry about it. Your executable file will now be created!
I'm not quite sure what you mean.
But I assume you mean either 1 of 2 things.
You want to create an executable .jar file
Eclipse can do this really easily File --> Export and create a jar and select the appropriate Main-Class and it'll generate the .jar for you. In windows you may have to associate .jar with the java runtime. aka Hold shift down, Right Click "open with" browse to your jvm and associate it with javaw.exe
create an actual .exe file then you need to use an extra library like
http://jsmooth.sourceforge.net/ or http://launch4j.sourceforge.net/ will create a native .exe stub with a nice icon that will essentially bootstrap your app. They even figure out if your customer hasn't got a JVM installed and prompt you to get one.
On the command line, navigate to the root directory of the Java files you wish to make executable.
Use this command:
jar -cvf [name of jar file] [name of directory with Java files]
This will create a directory called META-INF in the jar archive. In this META-INF there is a file called MANIFEST.MF, open this file in a text editor and add the following line:
Main-Class: [fully qualified name of your main class]
then use this command:
java -jar [name of jar file]
and your program will run :)
Take a look at WinRun4J. It's windows only but that's because unix has executable scripts that look (to the user) like bins. You can also easily modify WinRun4J to compile on unix.
It does require a config file, but again, recompile it with hard-coded options and it works like a config-less exe.
Jexecutable can create Windows exe for Java programs. It embeds the jars into exe file and you can run it like a Windows program.
You could use GCJ to compile your Java program into native code.
At some time they even compiled Eclipse into a native version.
Take a look at launch4j
Write a script and make it executable. The script should look like what you'd normally use at the command line:
java YourClass
This assumes you've already compiled your .java files and that the java can find your .class files. If java cannot find your .class files, you may want to look at using the -classpath option or setting your CLASSPATH environment variable.
Java Web Start is a good technology for installing Java rich clients off the internet direct to the end user's desktop (whether the OS is Windows, Mac or *nix). It comes complete with desktop integration and automatic updates, among many other goodies.
For more information on JWS, see the JWS info page.
As suggested earlier too, you can look at launch4j to create the executable for your JAR file. Also, there is something called "JExePack" that can put an .exe wrapper around your jar file so that you can redistribute it (note: the client would anyways need a JRE to run the program on his pc)
Exes created with GCJ will not have this dependency but the process is a little more involved.

Categories

Resources