- How to run JAR file on Linux
- How to install JRE on all major Linux distros
- Run JAR file from command line
- Run JAR file from GUI
- Closing Thoughts
- Related Linux Tutorials:
- 🐧 Как запустить JAR-файл на Linux
- Как установить JRE на все основные дистрибутивы Linux
- Запуск JAR-файла из командной строки
- Заключение
- How to Run Jar File in Ubuntu Linux
- Run jar files in Ubuntu
- Method 1: Using GUI
- Method 2: Using the Terminal
- Here’s how to set up the JAVA_HOME variable
- Как запустить jar в Linux
- Как запустить jar Linux
- Выводы
How to run JAR file on Linux
JAR files are those that have been coded and compiled using the Java programming language. In order to run these files on a Linux system, the Java Runtime Environment (JRE) software must be installed first. This is just a software package that allows the system to understand JAR files, and therefore gives it the ability to open and run them. Usually, the JRE package is not installed on most Linux distros by default, so we must first install Java, and then we can open the JAR file(s).
In this tutorial, we will show you how to install the Java Runtime Environment on all major Linux distributions. This will allow you to open JAR files regardless of what Linux distribution you are using. Then, we will use the newly installed software to open JAR files on Linux, via both command line and GUI.
In this tutorial you will learn:
- How to install the JRE on all major Linux distros
- How to open a JAR file via GUI
- How to open a JAR file via command line
Category | Requirements, Conventions or Software Version Used |
---|---|
System | Any Linux distro |
Software | Java JRE |
Other | Privileged access to your Linux system as root or via the sudo command. |
Conventions | # – requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command $ – requires given linux commands to be executed as a regular non-privileged user |
How to install JRE on all major Linux distros
The first thing we need to do is install the Java Runtime Environment so that we can open JAR files. You can use the appropriate command below to install the Java JRE with your system’s package manager.
$ sudo apt update $ sudo apt install default-jre
$ sudo dnf install java-latest-openjdk
To install the Java JRE on Arch Linux and Manjaro:
Run JAR file from command line
Running a JAR file from the command line is very simple. We can use the following syntax:
If the JAR file has a GUI component, it will launch on your screen. Otherwise, text will be output to your terminal.
Run JAR file from GUI
- In your file explorer, navigate to the directory where your JAR file is located. If you cannot run the JAR file by simply double clicking on it, then we will need to tell the system to open this file with the Java JRE that we installed earlier.
- Right click on the file and click on ‘Open with other application.’
- From your list of installed applications, choose the Java runtime environment that we installed earlier.
- Our Java program is now running as expected.
Closing Thoughts
In this tutorial, we saw how to run a JAR file on a Linux system. The only trick here is that we first need to install the Java runtime environment, which has varying instructions depending on the Linux distribution you are using. After installation of the JRE software, we are able to run JAR files from both command line and GUI.
Related Linux Tutorials:
Comments and Discussions
🐧 Как запустить JAR-файл на Linux
JAR- это файлы, которые были спрограмированны и скомпилированы с использованием языка программирования Java.
Для того чтобы запустить эти файлы в системе Linux, необходимо сначала установить программное обеспечение Java Runtime Environment (JRE).
Это просто пакет программного обеспечения, который позволяет системе понимать файлы JAR и, следовательно, дает ей возможность открывать и запускать их.
Обычно пакет JRE не установлен в большинстве дистрибутивов Linux по умолчанию, поэтому мы должны сначала установить Java, а затем открыть файл(ы) JAR.
В этом руководстве мы покажем вам, как установить Java Runtime Environment на все основные дистрибутивы Linux.
Это позволит вам открывать JAR-файлы независимо от того, какой дистрибутив Linux вы используете.
Затем мы будем использовать установленное программное обеспечение для открытия файлов JAR в Linux как через командную строку, так и через графический интерфейс.
Как установить JRE на все основные дистрибутивы Linux
Первое, что нам нужно сделать, это установить Java Runtime Environment, чтобы мы могли открывать файлы JAR.
Вы можете использовать соответствующую команду ниже, чтобы установить Java JRE с помощью менеджера пакетов вашей системы.
Чтобы установить Java JRE на Ubuntu, Debian, Linux Mint, MX Linux и Kali Linux:
$ sudo apt update $ sudo apt install default-jre
Чтобы установить Java JRE на Fedora, CentOS, Alma Linux, RockyLinux и Red Hat:
$ sudo dnf install java-latest-openjdk
Чтобы установить Java JRE на Arch Linux и Manjaro:
Запуск JAR-файла из командной строки
Запуск JAR-файла из командной строки очень прост.
Мы можем использовать следующий синтаксис:
Если JAR-файл имеет компонент GUI, он будет запущен на вашем экране.
В противном случае текст будет выведен на терминал.
Заключение
В этом руководстве мы рассмотрели, как запустить JAR-файл в системе Linux.
Единственная хитрость здесь заключается в том, что сначала нам нужно установить среду выполнения Java, которая имеет различные инструкции в зависимости от используемого дистрибутива Linux.
После установки программы JRE мы можем запускать JAR-файлы как из командной строки, так и из графического интерфейса.
How to Run Jar File in Ubuntu Linux
Downloaded a JAR file and don’t know how to use it? Learn how to run JAR files in Ubuntu based Linux distributions.
If you install any package having the .jar extension and try to execute it, it may throw an error saying «The file is not marked as executable»: And in this tutorial, I will walk you through how you can install its prerequisites and run Jar files in Ubuntu and other Linux with multiple methods.
Run jar files in Ubuntu
If you don’t know, JAR stands for Java ARchive so you must have a working Java environment. If you have Java installed, you should be able to run it. Check if Java is installed with:
If you see an error instead of the version number, install Java runtime environment using the following command:
sudo apt install default-jre
So let’s start with the first one.
Method 1: Using GUI
The first step is to open the file manager from the system menu and navigate to the jar file which you want to run.
Then, right-click on the jar app and select Properties .
From there, select Permissions and enable Allow executing file as program :
That made the file executable.
But you have yet to select which app it should use to run the jar files.
To select an Application to start the jar files, again, click on the jar file and choose the second option Open with Other Application and choose the OpenJDK Java Runtime option:
Now, you can start the jar application like you do with any other files by pressing the Enter key.
In my case, it was an installer and it started as it should:
Method 2: Using the Terminal
If you believe in efficiency, I’m about to show you the terminal method will complete the task in only three commands.
First, open the terminal and navigate to the directory where the jar file is located using the cd command:
Once done, use the chmod command with the +x flag to make the file executable:
And finally, you can use the Java command with the -jar flag to run the jar file:
Here’s how to set up the JAVA_HOME variable
Most of the users set the JAVA_HOME variable incorrectly. So we thought, why not make a dedicated guide to get things done correctly?
I hope you will find this guide helpful.
Как запустить jar в Linux
Java — это кроссплатформенный язык программирования, благодаря которому программы, написанные один раз, можно запускать в большинстве операционных систем: в Windows, Linux и даже MacOS. И всё это без каких-либо изменений.
Но программы, написанные на Java, распространяются в собственном формате .jar, и для их запуска необходимо специальное ПО — Java-машина. В этой небольшой статье мы рассмотрим, как запустить jar-файл в Linux.
Как запустить jar Linux
Как я уже сказал, для запуска jar-файлов нам необходимо, чтобы на компьютере была установлена Java-машина. Если вы не собираетесь ничего разрабатывать, вам будет достаточно Java Runtime Environment или JRE. Что касается версии, то, обычно, большинство программ работают с 7 или 8 версией. Если нужна только восьмая, то разработчики прямо об этом сообщают. Посмотреть версию Java и заодно убедиться, что она установлена в вашей системе, можно с помощью команды:
У меня установлена восьмая версия, с пакетом обновлений 171. Если вы получаете ошибку, что команда не найдена, то это значит, что вам нужно установить java. В Ubuntu OpenJDK JRE можно установить командой:
sudo apt install openjdk-8-jre
Если вы хотите скомпилировать пример из этой статьи, то вам понадобиться не JRE, а JDK, её можно установить командой:
sudo apt install openjdk-8-jdk-headless
Чтобы узнать, как установить Java в других дистрибутивах, смотрите статью по ссылке выше. Когда Java будет установлена, вы можете очень просто запустить любой jar-файл в Linux, передав путь к нему в качестве параметра Java-машине. Давайте для примера создадим небольшое приложение:
public class Main public static void main(String[] args) System.out.println(» Losst test app! «);
>
>
Затем скомпилируем наше приложение в jar-файл:
javac -d . Main.java
jar cvmf MANIFEST.MF main.jar Main.class
Теперь можно запустить наш jar-файл командой java с параметром -jar:
Таким образом вы можете запустить любой jar-файл, который собран для вашей версии Java. Но не очень удобно каждый раз открывать терминал и прописывать какую-либо команду. Хотелось бы запускать программу по щелчку мышки или как любую другую Linux-программу — по имени файла.
Если мы дадим программе право на выполнение:
И попытаемся её запустить, то получим ошибку:
Чтобы её исправить, нам понадобиться пакет jarwrapper:
sudo apt install jarwrapper
Теперь можно запускать java в Linux по щелчку мыши или просто командой.
Выводы
В этой небольшой статье мы рассмотрели, как запустить jar Linux с помощью java-машины, а также как упростить команду запуска. Если у вас остались вопросы, спрашивайте в комментариях!
Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.