Package java program as exe

How to Create an .Exe for a Java Program

The Java Packager tool compiles, packages, and prepares Java and JavaFX applications for distribution. The javapackager command is the command-line version.

– Oracle’s documentation

The javapackager utility ships with the JDK. It can generate .exe files with the -native exe flag, among many other things.

WinRun4J

  • Uses an INI file for specifying classpath, main class, vm args, program args.
  • Custom executable name that appears in task manager.
  • Additional JVM args for more flexible memory use.
  • Built-in icon replacer for custom icon.
  • [more bullet points follow]

WinRun4J is an open source utility. It has many features.

packr

Packages your JAR, assets and a JVM for distribution on Windows, Linux and Mac OS X, adding a native executable file to make it appear like a native app. Packr is most suitable for GUI applications.

– packr README

packr is another open source tool.

JSmooth

JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself.

– JSmooth’s website

JSmooth is open source and has features, but it is very old. The last release was in 2007.

JexePack

JexePack is a command line tool (great for automated scripting) that allows you to package your Java application (class files), optionally along with its resources (like GIF/JPG/TXT/etc), into a single compressed 32-bit Windows EXE, which runs using Sun’s Java Runtime Environment. Both console and windowed applications are supported.

– JexePack’s website

JexePack is trialware. Payment is required for production use, and exe files created with this tool will display «reminders» without payment. Also, the last release was in 2013.

InstallAnywhere

InstallAnywhere makes it easy for developers to create professional installation software for any platform. With InstallAnywhere, you’ll adapt to industry changes quickly, get to market faster and deliver an engaging customer experience. And know the vulnerability of your project’s OSS components before you ship.

– InstallAnywhere’s website

InstallAnywhere is a commercial/enterprise package that generates installers for Java-based programs. It’s probably capable of creating .exe files.

Executable JAR files

As an alternative to .exe files, you can create a JAR file that automatically runs when double-clicked, by adding an entry point to the JAR manifest.

Читайте также:  Java uri from file path

For more information

An excellent source of information on this topic is Excelsior’s article «Convert Java to EXE – Why, When, When Not and How».

See also the companion article «Best JAR to EXE Conversion Tools, Free and Commercial».

Compiling a java program into an executable

You can convert .jar file to .exe on these ways:

alt text

(source: viralpatel.net)
1- JSmooth .exe wrapper:

JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself. When no VM is available, the wrapper can automatically download and install a suitable JVM, or simply display a message or redirect the user to a web site.

JSmooth provides a variety of wrappers for your java application, each of them having their own behaviour: Choose your flavour!

2- JarToExe 1.8
Jar2Exe is a tool to convert jar files into exe files.
Following are the main features as describe in their website:

  • Can generate “Console”, “Windows GUI”, “Windows Service” three types of exe files.
  • Generated exe files can add program icons and version information.
  • Generated exe files can encrypt and protect java programs, no temporary files will be generated when program runs.
  • Generated exe files provide system tray icon support.
  • Generated exe files provide record system event log support.
  • Generated windows service exe files are able to install/uninstall itself, and support service pause/continue.
  • New release of x64 version, can create 64 bits executives. (May 18, 2008)
  • Both wizard mode and command line mode supported. (May 18, 2008)

3- Executor

Package your Java application as a jar, and Executor will turn the jar into a Windows exe file, indistinguishable from a native application. Simply double-clicking the exe file will invoke the Java Runtime Environment and launch your application.

EDIT: The above link is broken, but here is the page (with working download) from the Internet Archive. http://web.archive.org/web/20090316092154/http://mpowers.net/executor/

4- Advanced Installer
Advanced Installer lets you create Windows MSI installs in minutes. This also has Windows Vista support and also helps to create MSI packages in other languages.

Download: http://www.advancedinstaller.com/
Let me know other tools that you have used to convert JAR to EXE.

How do I create a Java application wrapped as an executable

Assuming you’re on Eclipse, in a Windows env, I usually proceed compiling end exporting my project accurately.

Doesn’t matter if it has «.jar» extension, you can «run» it just prompting something like this:

Читайте также:  METANIT.COM

I usually create a simple batch.txt file, and put that line inside.
Then i replace file extensione «.txt» with «.bat», and this way you could achieve the «double-clicked» styled start.

Otherwise, you could compile as «Runnable Jar» and it could be runned by «double-clicked» style app; but compile and be sure to point to the right mainclass in the manifest.

It’s very very broad answer, but your question isn’t specific enough.

1) Create simple Java Project

2) Put a new Class and name it «MainRunClass» with package com.runnable.testthis specific implementation:

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class MainRunClass
public static void main(final String[] args) final JFrame parent = new JFrame();
JButton button = new JButton();

button.setText("Click me to show dialog!");
parent.add(button);
parent.pack();
parent.setVisible(true);

button.addActionListener(new java.awt.event.ActionListener() @Override
public void actionPerformed(java.awt.event.ActionEvent evt) String name = JOptionPane.showInputDialog(parent,
"What is your name?", null);
>
>);
>
>

4) At prompt give it the «Launch Configuration put «Main Class\Project from the combolist, and the path of final export. You can leave «Export required jars and classes» in the same jar.

5) Double click it, or do a batch file as explained!

how can I create executable file for the program written on Java?

Источник

Конвертируем JAR в исполняемый (.exe) файл

Java-университет

Кратчайшая инструкция. Пишем простейшее тестовое приложение, допустим «Hi Amigo!» в файл HiAmigo.txt 100 раз.

 public class Main < public static void main(String[] args) throws IOException < File file = new File("C:\\temp\\HiAmigo.txt"); FileWriter fileWriter = new FileWriter(file); for (int i = 0; i < 100 ; i++) < fileWriter.write("Hi Amigo! \n"); >fileWriter.close(); > > 

Проверяем что все работает на этом этапе (это важно!) Конвертируем JAR в исполняемый (.exe) файл - 1Идем File -> Project Structure -> Artifacts -> + JAR -> From Modules with dependencies.. Конвертируем JAR в исполняемый (.exe) файл - 2Указываем путь к нашему Main.class: Конвертируем JAR в исполняемый (.exe) файл - 3Жмем ОК Жмем Build Artifacts — > Action -> Build Конвертируем JAR в исполняемый (.exe) файл - 4Появляется наш артефакт: Конвертируем JAR в исполняемый (.exe) файл - 5Удаляем наш тестовый файл «C:\\temp\\HiAmigo.txt» и запускаем JAR. Файл должен появиться еще раз. Если появился — все ок. Едем дальше. Качаем тулзу с сайта https://launch4j.sourceforge.net/ (Рекомендую версию 3.14, потом объясню почему). Устанавниваем запускаем. Нам нужно два поля. Указываем наш JAR и куда класть готовый .exe Конвертируем JAR в исполняемый (.exe) файл - 6Сейчас самое интересное. Представьте ситуацию что на машине где мы планируем использовать наше приложение не установлена JRE и нет возможности ее установить. Такое часто бывает по соображениям безопасности. К тому же хорошо бы обеспечить наше приложение более высоким уровнем автономности. Делаем следующее. Создаем отдельный каталог для нашего приложения, пусть OurApp. Внутри создаем папку JRE. Качаем JRE (в моем примере пусть будет jre-8u361-windows-i586) устанавливаем куда нибудь (если это готовый архив разархивируем) и выдергиваем из нее все файлы. Копируем все в \OurApp\JRE\ должно получиться примерно так: Конвертируем JAR в исполняемый (.exe) файл - 7В Launch4j переходим во вкладку JRE и в поле Bundled JRE paths: указываем имя каталога JRE Конвертируем JAR в исполняемый (.exe) файл - 8Жмем на шестеренку и выбираем любой файл для сохранения конфигурации типа file.xml Конвертируем JAR в исполняемый (.exe) файл - 9После нажатия на save появится наш exe. Конвертируем JAR в исполняемый (.exe) файл - 10Копируем exe и кладем рядом рядом с папкой JRE Конвертируем JAR в исполняемый (.exe) файл - 11Удаляем тестовый C:\temp\HiAmigo.txt. Запускаем exe и смотрим как создается новый. Вот и все. Теперь каталог можно OurApp можно архивировать и передавать куда угодно, exe отработает. Важно: Версия JRE в папке должна быть не ниже той на которой билдился артефакт. Проверяйте поле: Конвертируем JAR в исполняемый (.exe) файл - 12В моем случае возникли проблемы совместимости с x86 платформой и я использовал версию враппера 3.14, так как в ней можно явно указывать тип целевой архитектуры. В общем всем спасибо за внимание. Это была моя первая статья-инструкция, прошу не судить строго. Всем мир!

Читайте также:  Javascript object push element

Источник

Create Windows Executable (.exe) for Java Application

Launch4j is a cross-platform tool for wrapping Java applications distributed as jars in lightweight Windows native executable files. In this post, we will learn making such an executable file for a demo java application.

Step1 ) Create a java application

I am creating a very basic java class which simply displays a frame and some text on it. It also has the main() method which will start the application.

package com.howtodoinjava; import java.awt.Color; import java.awt.Font; import java.awt.Frame; import java.awt.Label; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JDialog; public class ApplicationMain extends JDialog < private static final long serialVersionUID = 1L; public ApplicationMain() < //Create a frame Frame f = new Frame(); f.setSize(500, 300); //Prepare font Font font = new Font( "SansSerif", Font.PLAIN, 22 ); //Write something Label label = new Label("Launch4j Maven Demo with HowToDoInJava.com"); label.setForeground(Color.RED); label.setFont(font); f.add(label); //Make visible f.setVisible(true); f.addWindowListener(new WindowAdapter() < public void windowClosing(WindowEvent e) < System.exit(0); >>); > public static void main(final String[] args) < new ApplicationMain(); >>

Step 2) Create maven file with launch4j configured in it

I have created a pom file for packaging the application as .exe file. If you feel something unclear, drop a comment.

 4.0.0 com.howtodoinjava JavaExeDemo jar 1.0-SNAPSHOT JavaExeDemo http://maven.apache.org UTF-8    org.apache.maven.plugins maven-compiler-plugin 2.5.1 1.6 1.6   org.apache.maven.plugins maven-shade-plugin 1.7.1  package shade    true shaded  com.howtodoinjava.Main     com.akathist.maven.plugins.launch4j launch4j-maven-plugin 1.5.1  l4j-clui package launch4j  gui $/$-$-shaded.jar $/howtodoinjava.exe http://java.com/download com.howtodoinjava.ApplicationMain anything  application.ico 1.6.0 preferJre  1.0.0.0 $ $ 2012 howtodoinjava.com 1.0.0.0 1.0.0.0 $ howtodoinjava.com howtodoinjava howtodoinjava.exe         

Step 3) Create .exe file

To make the exe file for above java program, run maven command:

Above command will create the “howtodoinjava.exe ” file in your project’s target folder. Double click on .exe file will open the window like this.

Launch4j maven demo to create java executable

If you want to download source code of above application, click on below given download link.

Happy Learning !!

Источник

Оцените статью