Как запустить jar linux
Перейти к содержимому

Как запустить jar linux

  • автор:

How to Run Jar File in Ubuntu Linux

Got a Jar file but struggling to execute it? Learn how to run a Jar file in Ubuntu and other Linux distributions.

How to execute Jar file in Ubuntu and other distributions

A Jar file is basically a Java executable file. So you must have Java installed on your system. If you have Java installed in your Ubuntu, you should be able to run it either by double clicking or by selecting from right click options.

The problem here is that most Linux distributions don’t come with Java pre-installed. So please make sure to install Java on Ubuntu or whichever distribution you are using.

You only need the Java Runtime Environment and you can install it using the command below in Ubuntu-based distributions:

Even with Java installed, sometimes running a Java application is not as straightforward as double-clicking the icon. You might have to go through a few steps.

When I tried to open the .jar file by double clicking, I was presented with the following error:

Ubuntu Run Java Jar Error

File not executable error

Fixing this error is very trivial. Right click the .jar file, and open properties.

Ubuntu Run Java Jar Menu

Right click on Jar file and click Properties

Now in the properties menu, open the ‘Permissions’ tab. Enable the ‘Allow executing this file as program’ checkbox.

Ubuntu Run Java Jar Permission Set

Enable Execution of the file under the Permissions tab

Now, you can simply double click the .jar file to launch the application, AndroMouse in my case. You can see that it works without any problems.

Ubuntu Run Java Jar App Running

Java App Running

You have to keep in mind that you have to enable the ‘Allow executing as program’ permission for every .jar application you download. It is disabled by default as a security measure. You should enable it only for the applications that you trust and know are safe.

Further troubleshooting Jar file not running on Linux

Even if you have Java Runtime Environment installed and execution permission set, in some older versions of Ubuntu, the Jar file won’t run. Here’s a fix for that.

Right click on the .jar file and choose the option “Open With Other Application“:

Ubuntu Jar Files

Now on the next screen, select the option Show other applications:

In other applications, if you do not find option for Java, install the Java Runtime Environment first. Normally, you should be able to see the option Open With OpenJDK Java x Runtime. Select it and successfully run it.

Enjoy running Jar file on Ubuntu!

Bonus tip: Run jar file from the terminal

Running the jar file from terminal has its advantages. It may show helpful error messages if the jar file doesn’t run successfully.

In the terminal, use the command like this:

I hope this short guide was useful to all of you. Which Java based applications do you use? Do you have any other problems with them? Let me know in the comments below!

Запуск Java классов и JAR-ов не по учебнику

Меня давно занимала мысль как в Linux-е запускать программы на Java без вспомогательных Bash скриптов. Я не видел приемлемого решения, если не считать способ «bash script payload», когда в конец скрипта помещается бинарный файл.

Но на прошлой неделе случайно наткнулся на модуль ядра binfmt_misc, с помощью которого можно перехватить исполнение файла по его magic number. Для этого через update-binfmts добавляется собственный обработчик для получения имени исполняемого файла и аргументов пользователя.

Первое открытие

Как оказалось в моей Ubuntu 16.04 уже зарегистрирован обработчик для JAR файлов:

Отдав команду chmod +x foo.bar я радостно потирал руки, но реальность оказалось сурова — запуск ./foo.jar выдал следующее:

Погуглив, я нашел обросший мхом баг bugs.java.com/bugdatabase/view_bug.do?bug_id=6401361 Как оказывается сборка через Maven не добавляет «0xcafe» в начало JAR файла. Не менее безответственно ведет себя и плагин maven-assembly-plugin. Что не нравится /usr/bin/jexec, зарегистрированному обработчику по умолчанию.

Погуглив еще, я нашел решение проблемы через установку пакета jarwrapper. После установки добавляется новый обработчик /usr/bin/jarwrapper и страховка /usr/bin/jardetector (проверяет по META-INF что это действительно JAR). Но изучив код обработчика мне не понравилась куча лишней работы, которую делает скрипт запуская множество вспомогательных программ.

Поэтому решением стал собственный обработчик:

Дальше открываем файл sudo gedit /var/lib/binfmts/jar и регистрируем обработчик заменив строчку с /usr/bin/jexec на /usr/bin/jarinvoke. На самом деле это плохое решение и лучше создать собственную группу (об этом ниже), но для первичного понимания сойдет.

Для вступления изменений в силу может потребоваться выполнить:

После чего можете запускать JAR файлы как любые другие исполняемые файлы.

Исполняемые классы

Теперь можно идти дальше и сделать из Java классов исполняемые файлы, где jarwrapper не сможет помочь. Обработчик будет работать только для классов с пакетом по умолчанию (т.е. классы с отсутствующим package заголовком). Может можно сделать и лучше, но мне хватило такой функциональности для «скриптования» на Java:

После чего регистрируем собственный обработчик (этим же способом можно создать новый обработчик для JAR-ов не редактируя /usr/bin/jexec):

Можно пойти и дальше, сделав более сложный обработчик, который по импорту классов будет определять какие библиотеки добавить в CLASSPATH из

/.m2, но это отдельная история. Сейчас интересен взгляд со стороны, замечания, дополнения, если таковые есть. После чего думаю оформить это в deb пакет и выложить всё на гитхабе.

How can I execute a .jar file from the terminal

I know that to execute a file, I use the . command, then the file name with a space between them. But I’m trying to execute a .jar file using the . and it does not work. I went into the properties and marked it as executable and made it run with Java.

Is there a way to execute a file with Java in the Bash Terminal? I am trying to execute a Minecraft.jar file

I am trying to execute the Minecraft.jar file.

9 Answers 9

The . syntax can only be used to run (by «sourcing») shell scripts.

You’ll need to use the java command to run a .jar file:

If you don’t have java installed, you can fix that by installing the default-jre ¹ package. You can see if you already have java installed by running in a terminal:

[1]: This will install the default openjdk Java runtime. You can use openjdk-8-jre , or openjdk-7-jre , or openjdk-6-jre instead, if you prefer — whichever is available on your version of Ubuntu.

Linux is perfectly capable of running a foreign binary, like a JAR file. This is how Wine works, for example. To run JAR files as executable do the following in a console

Cd to your JAR file and change it to executable (you can also do this through file properties in Nautilus)

Run your jar file just as if it was any other binary executable or shell script

Note: Be sure you have binfmt_misc linux kernel module loaded. If you use your custom compiled kernel without this module, binfmt-support won’t work.

If it is an executable jar, then

Not all jar-Archives contain an executable class, declared to be started in the Manifest file, but if there is, this will work.

Btw.: You don’t start most programs from the shell with the dot. The dot is a shortcut for source , and it only works in the bash and some other shells, to include a script in the scope of the current session.

A compiled binary xybin is simply started with its name if it is in the path:

or, with its absolute path:

or with its relative path:

or if you happen to be in the directory of the file, with this relative path:

The file has to be marked executable for you (see: chmod). All of the above is true for shellscripts too, but they often have an extension .sh, and you can start a shellscript by invoking the interpreter, and then it needn’t be marked executable:

If you don’t want to start a new bash, you can use source, and you do so, to consume function definitions, aliases and variable settings.

Как запустить 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-машине. Давайте для примера создадим небольшое приложение:

Затем скомпилируем наше приложение в jar-файл:

javac -d . Main.java jar cvmf MANIFEST.MF main.jar Main.class

Теперь можно запустить наш jar-файл командой java с параметром -jar:

java -jar main.jar

Таким образом вы можете запустить любой jar-файл, который собран для вашей версии Java. Но не очень удобно каждый раз открывать терминал и прописывать какую-либо команду. Хотелось бы запускать программу по щелчку мышки или как любую другую Linux-программу — по имени файла.

Если мы дадим программе право на выполнение:

chmod u+x ./main.jar

И попытаемся её запустить, то получим ошибку:

Чтобы её исправить, нам понадобиться пакет jarwrapper:

sudo apt install jarwrapper

Теперь можно запускать java в Linux по щелчку мыши или просто командой.

Выводы

В этой небольшой статье мы рассмотрели, как запустить jar Linux с помощью java-машины, а также как упростить команду запуска. Если у вас остались вопросы, спрашивайте в комментариях!

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

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