Launch4j как пользоваться java в exe
Перейти к содержимому

Launch4j как пользоваться java в exe

  • автор:

Launch4j как пользоваться java в exe

<path>, <minVersion>, <maxVersion> The <path> property is used to specify absolute or relative JRE paths, it does not rely on the current directory or <chdir>. Note that this path is not checked until the actual application execution.
Launch4j 3.50 <path> is now required and always used for searching before the registry in order to ensure compatibility with latest runtimes which by default do not add registry keys during installation.
Launch4j 3.50 <minVersion> and <maxVersion> are now considered during path and registry search, previously the version was checked only during registry search. The first runtime version matching the given range will be used. <path> alone Search for JREs using specified paths, if not found stop with error.

Default: <path>%JAVA_HOME%;%PATH%</path>
Bundled: <path&gtjre</path>
Advanced: <path>%HKEY_LOCAL_MACHINE\SOFTWARE\UnusualJavaVendor\JavaHome%;%JAVA_HOME%;%PATH%</path> <path> + <minVersion> [+ <maxVersion>] Use path search first, if Java cannot be located then perform a registry search. If that fails display an error message and optionally open the Java download page.

Importing 1.x configuration

Importing 2.x/3.x configuration to 3.50

Ant task

You can also define the entire configuration in the task, but it will not be possible to edit such a file in the GUI mode. All paths except for <chdir>, <jre><path> and jarPath are calculated using the basedir project attribute.

Name already in use

Work fast with our official CLI. Learn more about the CLI.

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Make your JAR a standalone executable

Hello! I was doing some researches about how can I convert my complex JAR program (12 MB) in a standalone executable that can be runned without JRE installed. I am using Launch4J; in this repository I’ll show you how to use it.

Java installed (For developer machine);

Your JAR (Make sure it runs correctly in a machine with Java installed);

A .ico file as icon for your exe built file (You can download them for example for free from https://www.iconfinder.com or make/buy custom icons, or google .ico);

A JRE to bundle to your exe built file (Read below).

Why do I need a JRE bundled?

Java applications, as you know, can be executed thanks to a Java Virtual Machine (JVM), that can be a JRE (Java Runtime Environment) or a JDK (Java Development Kit).

Without a JVM, Java applications just cannot be executed and they look as raw archives to a normal user. In Windows systems for customers, Java is normally NOT installed, so customers would be very confused and annoyed to go to Java website and download JVM to run their jar file. This could cause potential loss of customers and downvote your product.

Launch4J allows you to bundle a JVM inside exe file, so:

  • You can ensure to run your application with a minimum JVM version;
  • Customers don’t have to worry about downloading Java on their machines;
  • So basically your application becomes portable. 😛

What JRE do I need?

Try to pick the lowest JRE possible that can run your project. Make a compromise between compatibility and security. Oracle fixes Java vulnerabilities by updating their JVMs, so it is always recommended to choose a good updated JRE.

You can download the latest JRE if you need best security possible and don’t need compatibility with older machines. You can download older JRE if compatibility is a concern from you enough to withdraw security.

  • Latest JRE: http://www.oracle.com/technetwork/java/javase/downloads/jre8-downloads-2133155.html (Or google «JRE download»)
  • Older JREs: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-javase8-2177648.html (Pick a 32 bit version)

Choose .tar.gz archive for download.

In this project I’ll assume your Java project dir has this path for ease of understanding: C:\Users\Finalgalaxy\Documents\java_projects\proj1\

  • Download everything necessary;
  • Unzip JRE downloaded inside proj1 folder, so that you have JRE unpacked in C:\Users\Finalgalaxy\Documents\java_projects\proj1\jre1.8.0_151\ (Using jre1.8.0_151 as example);
  • Follow the images.

Basic

  • Output file: the location where your exe file is built in;
  • Jar: the jar that needs to be packaged into a built exe file;
  • Icon: your .ico file;
  • Header type: how your java program looks like (Does it have a GUI?)
  • Single instance: check «Allow only a single instance of the application» and place as mutex your app name (or a substring) to ensure processes containing that mutex won’t run at same time;
  • Bundled JRE path: this is the folder of your JRE, type in jre1.8.0_151. Type bin\jre1.8.0_151 if you placed JRE in a subfolder called bin;
  • Min JRE version: this ensures that your applications runs at least on the minimum JRE version that is set (For example 1.8.0).

There are many other options to check them out.

About

Make your JAR a standalone executable with Launch4J (Step-by-step tutorial for newbies).

Convert a JAR to a Windows Executable (.EXE) inside a Maven Project

Wrap Java application distributed as a JAR in native Windows executable with embedded Java Runtime Environment (JRE)

Nitish Borade

Javarevisited

How do you distribute a Java-based desktop application to your Windows customers? The jar created by the application build, which then needs a Java Runtime Environment (JRE) to be installed on the client workstation, OR as a Windows Executable ( exe ) with JRE packaged, removing the requirement for the customer to install the JRE necessary to execute the Java-based application.

With Launch4J and Maven, you can do precisely that: create a Windows executable from the JAR and bundle it with the JRE into a final zip file that you can provide to clients. The consumer just has to simply unzip the file and double-click the executable to run the application.

Launch4J

Launch4j encapsulates jars in native Windows executables, allowing them to be executed just like any other Windows application.

Using Launch4J you may either package a JRE, have it look on the computer for one already installed or you also have the option of providing a direct URL to download one.

A Maven-based project is required for the approach outlined in this article which will compile your application into a jar and wrap it into an exe using the Maven Plugin for Launch4j, before bundling it with a Java Runtime Environment.

Maven Plugin for Launch4J

The Maven plugin for Launch4j generates an executable as a part of the Maven build process. It supports Maven 2.0.4 and above.

By including the following plugin in your project’s pom.xml file, you may define the Launch4j runtime configurations. By default, the Launch4j plugin is bound to the package phase, but it is run after the application's JAR is created.

When the executable is launched, it will seek for the JRE in the directory specified relative to the executable, which we will package in a zip file together with the exe in the following part.

If your application requires administrator privileges, include the following in the manifest file ( src/main/resources/<project-artifact-id>.manifest.xml ) configured in the plugin above.

Package the executable with JRE

Following the creation of the executable, you want Maven to bundle everything together. This is accomplished using the assembly plugin in pom.xml .

The following is a basic assembly specification ( src/main/resources/assembly.xml )for creating a zip file including the executable and a JRE.

The example bundles the JRE as specified by the JAVA_HOME environment variable on the machine where the application is built.

Alternately, a preferable option for is downloading the JRE from your organization’s central maven artifactory and unpacking it in a place that is subsequently picked by the assembly plugin.

Finally, execute the maven command to bring everything together.

A zip will be created in the target folder which will have the following structure

My GitHub repository has an example maven project that converts a jar formatted Java application into an exe and packs it with the JRE.

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

Кратчайшая инструкция. Пишем простейшее тестовое приложение, допустим «Hi Amigo!» в файл HiAmigo.txt 100 раз. Проверяем что все работает на этом этапе (это важно!) Конвертируем 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, так как в ней можно явно указывать тип целевой архитектуры. В общем всем спасибо за внимание. Это была моя первая статья-инструкция, прошу не судить строго. Всем мир!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *