How to run jar files in linux

How to run .jar file on unix?

You must be trying to launch a jar compiled with JDK6, with a local java1.5.

 javac -source 1.5 -target 1.5 -bootclasspath /path/to/jre1.5/lib/rt.jar 

to check if you can generate 1.5 bytecode compatible.

Have you tried using a newer version of Java on your Unix system?

If you control the jar file, could you target Java 1.5 when it’s compiled?

UnsupportedVersionError means that you have compiled the Java source code with a newer version of Java than what you’re trying to run it with. Java is downwards compatible (newer versions of Java can run Java programs compiled with older versions), but not upwards compatible (older versions of Java cannot run Java programs compiled with newer versions).

You say you’re using Java 5 on Unix. Did you compile it using Java 6 on Windows? Then it’s obviously not going to work.

  • Compile your source code using Java 5 on Windows (the safest option)
  • Use the compiler flags: -source 1.5 -target 1.5 while you compile (this will not protect you against using Java 6-only classes from the standard library, so this is not a full guarantee that your program will run without errors on Java 5)
  • Upgrade to Java 6 on Unix

Recompile your application with Java 5 on your Windows machine.

(Java 6 generates Java 6 compatible byte code by default to use new facilities. The easiest for you is to install a Java 5 JDK and use it to recompile your application)

  • Check that JDK or JRE is installed. Install if it is not.
  • set JAVA_HOME= # JDK/JRE home directory
  • $JAVA_HOME/bin/java -jar file.jar

You should also keep in mind that JVM are not forward compatible, so if you’ve made a jar-file using JDK 1.6, it won’t work with JDK 1.5!

In this case you may either:

  • install JDK 1.6 to Unix
  • recompile the jar with -target 1.5 flag (but you may get any sort of errors due to API incompatibilities, so the first way is much better)

I faced the same problem. This is because the runtime and compile time JDK versions are different. Make the jar through eclipse after changing the java compiler version. The following link helped me.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.14.43533

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

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.

jar file not marked as executable

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.

Читайте также:  Qualcomm atheros ar9285 wireless network adapter драйвер linux

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 :

make file executable using file manager

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:

Running Jar file in Ubuntu with double click

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:

running jar file in Ubuntu

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, её можно установить командой:

Читайте также:  Linux команда дата создания файла

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.

Источник

How can I execute a .jar file from the terminal

I am trying to execute a Minecraft.jar file

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 the Minecraft.jar file.

Hello and welcome, jaorizabal. I slightly corrected your question. Maybe you can install a spell checker for your browser, to improve the next question yourself. Another hint: For text issues, you may mark text with your mouse in the terminal, and then paste it into the edit field of your browser (and elsewhere) with a middle click on the scroll wheel. Then you can layout your code with the buttons at the edit field. This is much faster than taking a screen shot, and uploading it.

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

sudo apt-get install binfmt-support 

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.

Читайте также:  Information about disk linux

Thanks! This is exactly what I was looking for. It’s better than using java -jar because it doesn’t require the host program to know that it is a java program, and it’s better than using a script because you don’t have to worry about passing through STDIN and OUT.

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.

You might as well want to make a nice entry for the application in Unity. execute the following commands:

gedit ~/.local/share/applications/minecraft.desktop 

In the window that pops up, copy and paste the following:

[Desktop Entry] Type=Application Name=Minecraft Comment=Click here to play Minecraft Exec=java -jar /path/to/minecraft.jar Icon=/path/to/minecraft/icon.png Terminal=false Categories=Game; 

You might need to log out and back in to see the effects. 🙂 Also you need to search the internet for a nice lookin Minecraft icon since they don’t provide one with the download..

  1. Open a command prompt with CTRL + ALT + T
  2. Go to your «.jar» file directory. If your Ubuntu version / flavour supports it, you should be able to right click on your «.jar» file’s directory and click «Open in Terminal»
  3. Type the following command:

This way your «.jar» file will execute.

Install jarwrapper. After that (and by adding the executable bit) you can start the jar file just by entering the jarfile name.

sudo apt-get install jarwrapper 

This works by using binfmt to add support for a new binary format to the kernel.

 java -jar /home/username/.minecraft/launcher.jar 

New answer to an old question

Executing a jar file using the regular syntax ./app.jar (instead of java -jar ), is easy to achieve, as explained here: how to create executable jars.

Basically, JAR is a variant of ZIP, which allows random bytes to be pre/appended to the JAR without corrupting it. This means it is possible to prepend a launcher script at the beginning of the jar to make it «executable».

Here is a simple example of turning a «normal» jar into an executable one:

# Append a basic launcher script to the jar cat \ <(echo '#!/bin/sh')\ <(echo 'exec java -jar $0 "$@"')\ <(echo 'exit 0')\ original.jar >executable.jar # Make the new jar executable chmod +x executable.jar 

With this, you can now run ./executable.jar instead of java -jar original.jar . This works on all unix like systems including Linux, MacOS, Cygwin, and Windows Linux subsystem.

Источник

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