- How to Run Jar File in Ubuntu Linux
- How to execute Jar file in Ubuntu and other distributions
- Further troubleshooting Jar file not running on Linux
- Как создать и выполнить файл .Jar в терминале Linux
- Как создать JAR-файл в Linux
- Java: работа с jar-архивами из консоли Linux
- Извлечение объектов из архива
- Создание jar-архива
- Просмотр содержимого jar-архива
- Добавление объектов в jar-архив
- Дополнение
- Running .jar File on Linux
- 4 Answers 4
- Creating and Executing a .jar File in Linux Terminal
- Requirements
- Create Jar files
How to Run Jar File in Ubuntu Linux
Last updated October 29, 2019 By Abhishek Prakash 19 Comments
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:
Fixing this error is very trivial. Right click the .jar file, and open properties.
Now in the properties menu, open the ‘Permissions’ tab. Enable the ‘Allow executing this file as program’ checkbox.
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.
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“:
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!
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!
Like what you read? Please share it with others.
Источник
Как создать и выполнить файл .Jar в терминале Linux
JAR (Java ARchive) – это независимый от платформы формат файла, используемый для объединения многих файлов классов Java и связанных с ними метаданных и ресурсов, таких как текст, изображения и т. д., в один файл для распространения.
Он позволяет Java-средам эффективно разворачивать целое приложение в одном архиве и предоставляет множество преимуществ, таких как безопасность, его элементы могут быть сжаты, сокращено время загрузки, позволяетcz уплотнение пакетов и управление версиями, поддерживает переносимость.
Он также поддерживает упаковку для расширений.
В этой статье мы покажем, как создать простое приложение Java и связать его с JAR-файлом и продемонстрируем, как выполнить файл .jar из терминала Linux.
Для этого у вас должен быть установлен инструмент командной строки java для запуска приложения Java и флаг -jar для выполнения программы, инкапсулированной в файл JAR.
Когда этот флаг используется, указанный JAR-файл является источником всех пользовательских классов, а другие параметры пути класса игнорируются.
Как создать JAR-файл в Linux
1. Сначала начните с написания простого Java-класса с основным методом для приложения TecmintApp для демонстрационных целей.
Скопируйте и вставьте следующий код в файл TecmintApp.java.
Сохраните файл и закройте.
2. Затем нам нужно скомпилировать и упаковать класс в JAR-файл, используя утилиты javac и jar, как показано ниже:
3. Создана Ounce tecmint app.jar, теперь вы можете выполнить файл с помощью команды java, как показано ниже:
Из вывода приведенной выше команды видно, что мы столкнулись с ошибкой. JVM (Java Virtual Machine) не смог найти наш основной атрибут, поэтому он не смог найти основной класс, содержащий основной метод (public static void main (String [] args)).
Файл JAR должен иметь манифест, содержащий строку в форме Main-Class: classname, которая определяет класс с основным методом, который служит отправной точкой нашего приложения.
4. Чтобы исправить вышеуказанную ошибку, нам нужно будет обновить JAR-файл, чтобы включить атрибут манифеста вместе с нашим кодом.
Давайте создадим файл MANIFEST.MF.
Скопируйте и вставьте следующую строку в файл MANIFEST.MF.
Сохраните файл и добавьте файл MANIFEST.MF в наш tecmintapp.jar, используя следующую команду:
5. Наконец, когда мы снова выполним файл JAR, он должен предоставить нам ожидаемый результат, как показано на выводе:
Для получения дополнительной информации см. Man-страницы java, javac и jar.
Источник
Java: работа с jar-архивами из консоли Linux
Извлечение объектов из архива
Распаковать архив ojdbc14-10.2.0.4.jar в текущую директорию:
-x — extract, распаковать;
-f — file, файл, который необходимо распаковать;
В результате получим содержимое архива:
Извлечь только определённый файл или каталог, например — только папку oracle из архива ojdbc14-10.2.0.4.jar :
Извлечь только определённый файл:
Необходимые каталоги (в данном случае oracle/sql ) будут созданы автоматически.
Создание jar-архива
-v — verbose, будет выводить полную информацию о действиях;
-0 — zero, не будет сжимать файлы перед добавлением в арихв;
-f — file, направить всё в файл;
-c — create, создать архив;
-C — change, сменить каталог на время выполнения операции.
Создадим простой архив oracle.jar в который заархивируем содержимое каталога oracle :
То же, но в подробном режиме:
Видно, что файлы сжимаются. Избежим этого, добавим -0 :
Видим, что файлы добавляются в архив вместе с директориями. Что бы избежать этого, и файлы размещать в корне архива — используем опцию -C :
Файл file.d находится в корне архива, т.к. перед выполнением добавления его в архив — архиватор сменил текущую директорию на or .
Просмотр содержимого jar-архива
-f — file, файл архива;
-t — table, список содержимого;
-v — verbose, более полная инфомрация.
Добавление объектов в jar-архив
-u — update, обнвоить содержимое архива.
И добавим его в имеющийся архив oracle.jar :
При обновлении архива — так же можно использовать опцию -C (change).
Дополнение
Простой способ найти файл, который находится в каком-то jar -архиве, но вы не знаете в каком именно:
Источник
Running .jar File on Linux
I have a .jar file that reads two files from within its current folder and produces as output a .txt file and a separate folder with multiple other .txt files. This works perfectly in Windows using this code to create the directory:
I used the instructions here: https://askubuntu.com/questions/192914/how-run-a-jar-file-with-a-double-click to set up my .jar file to run on a simple double-click, but as of right now, it does nothing when double-clicked. My guess is that the above line of code does not translate well to Linux. Anybody know how to resolve this?
4 Answers 4
First, try running it on the command-line, with
The user.dir property is cross-platform (see here) so it should not be the problem. However, are you using correct file separators? Remember it’s ‘/’ on UNIX and ‘\’ on Windows.
Try java -jar Jarname.jar and pass other files as arguments after this command
The code line you gave works fine on linux.
My best guess is that you’re then trying to use this directory path by adding a windows-specific path separator (like path + «\subdir») which isn’t appropriate for linux (you should build a new File object instead).
Either that, or your jar file isn’t being executed at all. Have you tried doing something very simple in your jar file to see if anything is being run? Have you tried running your jar with java -jar myapp.jar to see if any exceptions are thrown or error messages displayed?
You will need to manually tweak your build process to get the jar file marked as executable. In your build xml file, there is a target, «-post-jar», that is called after the jar is built. You’ll need to make that target and use Ant’s chmod task to modify your jar. Once you do that it will occur every time you make a jar file in that project.
It will run fine as long as you have a JRE installed.
Источник
Creating and Executing a .jar File in Linux Terminal
JAR – Java Archive. It is like a zip file but for java classes. It combines all the .class files in Java into a single .jar file. It is used to download all java classes on HTTP in a single operation. These can be created using the “jar” CLI tool. It also has an optional META-INF which can include files like –
- MANIFEST.MF – manifest file is used to define the extension and package-related data.
- INDEX.LIST – It contains location information for packages defined in an application or extension.
- x.SF – This is the signature file where ‘x’ is the base file name.
- x.DSA – This file stores the digital signature of the corresponding signature file.
- services/ – This directory stores all the service provider configuration files.
The most common and majorly used file is MANIFEST.MF
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Requirements
Java (JDK + JRE) must be installed. Check by using command –
Create Jar files
Let us consider 4 class files – Class1, Class2, Class3, Class4
Источник