How to add multiple jar files in classpath in linux
Okay, I’m very new to linux and command line, and fairly new to java. I got an internship building a java program. I finally got it done on my machine (windows) and now I have to migrate it to a linux machine to test and then have it run as an executable. I have done much reading and researching on linux and understanding classpaths but it is still all very hard to fully comprehend. It’s just not clicking for me yet. Can anyone explain the purpose of classpath in a simplified way using examples? One of the most confusing aspects to me is actually defining the physical path to the jar. Do I start all the way from usr or do I only need to begin from the jvm folder? If it matters, my java program is not located in the jvm folder. Can anyone shed some light for me? EDIT: thank you guys very much for your help, I can’t say that I’m fully in the clear but my understanding of my situation is a lot better.
5 Answers 5
Say you have multiple jar files a.jar,b.jar and c.jar. To add them to classpath while compiling you need to do
$javac -cp .:a.jar:b.jar:c.jar HelloWorld.java
$java -cp .:a.jar:b.jar:c.jar HelloWorld
You use the -classpath argument. You can use either a relative or absolute path. What that means is you can use a path relative to your current directory, OR you can use an absolute path that starts at the root / .
bash$ java -classpath path/to/jar/file MyMainClass
In this example the main function is located in MyMainClass and would be included somewhere in the jar file.
For compiling you need to use javac
bash$ javac -classpath path/to/jar/file MyMainClass.java
You can also specify the classpath via the environment variable, follow this example:
bash$ export CLASSPATH="path/to/jar/file:path/tojar/file2" bash$ javac MyMainClass.java
For any normally complex java project you should look for the ant script named build.xml
So if the java program I am trying to compile is named SnortMonitor would your example change to: bash$ java -classpath path/to/jar/file SnortMonitor
Ah for compiling you need to call javac instead of java , but you still use -classpath and the source directory.
thankyou for your help but could you please be a little more specific? Maybe it’s because of my lack of understanding. When I write «javac SnortMonitor.java, I get a list of errors and I know its because I need to include 2 jar files from a directory called jsendnsca. Do I need to include those jars in the classpath each time I compile and run the program?
I believe that if you specify the environment variable CLASSPATH it will use that — I’ll edit my answer to make it more clear how to do that.
The classpath is the place(s) where the java compiler (command: javac) and the JVM (command:java) look in order to find classes which your application reference. What does it mean for an application to reference another class ? In simple words it means to use that class somewhere in its code:
When you try to compile this (javac) the compiler will need the AnotherClass class. The same when you try to run your application: the JVM will need the AnotherClass class. In order to to find this class the javac and the JVM look in a particular (set of) place(s). Those places are specified by the classpath which on linux is a colon separated list of directories (directories where the javac/JVM should look in order to locate the AnotherClass when they need it).
So in order to compile your class and then to run it, you should make sure that the classpath contains the directory containing the AnotherClass class. Then you invoke it like this:
javac -classpath "dir1;dir2;path/to/AnotherClass;. ;dirN" MyClass.java //to compile it java -classpath "dir1;dir2;path/to/AnotherClass;. ;dirN" MyClass //to run it
Usually classes come in the form of «bundles» called jar files/libraries. In this case you have to make sure that the jar containing the AnotherClass class is on your classpaht:
javac -classpath "dir1;dir2;path/to/jar/containing/AnotherClass;. ;dirN" MyClass.java //to compile it java -classpath ".;dir1;dir2;path/to/jar/containing/AnotherClass;. ;dirN" MyClass //to run it
In the examples above you can see how to compile a class (MyClass.java) located in the working directory and then run the compiled class (Note the «.» at the begining of the classpath which stands for current directory). This directory has to be added to the classpath too. Otherwise, the JVM won’t be able to find it.
If you have your class in a jar file, as you specified in the question, then you have to make sure that jar is in the classpath too , together with the rest of the needed directories.
java -classpath ".;dir1;dir2;path/to/jar/containing/AnotherClass;path/to/MyClass/jar. ;dirN" MyClass //to run it
or more general (assuming some package hierarchy):
java -classpath ".;dir1;dir2;path/to/jar/containing/AnotherClass;path/to/MyClass/jar. ;dirN" package.subpackage.MyClass //to run it
In order to avoid setting the classpath everytime you want to run an application you can define an environment variable called CLASSPATH.
In linux, in command prompt:
export CLASSPATH="dir1;dir2;path/to/jar/containing/AnotherClass;. ;dirN"
or edit the ~/.bashrc and add this line somewhere at the end;
However, the class path is subject to frequent changes so, you might want to have the classpath set to a core set of dirs, which you need frequently and then extends the classpath each time you need for that session only. Like this:
export CLASSPATH=$CLASSPATH:"new directories according to your current needs"
Как запустить 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.
How to install a .jar file
You can’t really ‘install’ a tgz or jar file. A tgz is just an archive, as well as a jar. You could manually install it, but not with the default Debian/Ubuntu package manager. You will need to install Java from the software center. For minecraft, download the file, and extract it if needed. Then just read the instructions or find the file you need to use to install or launch the program. Perhaps you would benefit from reading the Ubuntu manual: ubuntu-manual.org
3 Answers 3
You must installed java on your system to install .jar files.Syntax to install .jar files was,
In this case,you have Minecraft.jar file,so type the below command in terminal
A .jar file is a Java Programming Language file. You can do this, since it’s Minecraft:
- Create a new folder in your user folder. (It can also be recognized as a «~».)
- Move Minecraft and an icon (call it «Minecraft» and make sure it’s a .png, and if not, convert it using an online tool.) to a folder you will keep it in. Use ~/.apps/Minecraft , for the sake of usage.
- Make a file, on your desktop. Create a new file, name it «Minecraft.desktop». More info here. Copy-and-paste this after you open it with a text editor:
[Desktop Entry] Name=Minecraft Exec=java -jar ~/.apps/Minecraft/Minecraft.jar Icon=~/.apps/Minecraft/Minecraft.png Type=Application Categories=Game;
sudo apt-get install default-jre chmod +x ~/.apps/Minecraft/Minecraft.jar chmod +x ~/Desktop/Minecraft.desktop
Java/OpenJDK: How to add JAR to classpath
After my distribution (Debian Buster) upgraded to the latest OpenJDK 11 this command is no longer working. This is what I am now getting:
Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/ws/http/HTTPException at microsoft.exchange.webservices.data.core.ExchangeService.findItems(ExchangeService.java:976) at microsoft.exchange.webservices.data.core.ExchangeService.findAppointments(ExchangeService.java:1264) at microsoft.exchange.webservices.data.core.ExchangeService.findAppointments(ExchangeService.java:1285) at com.zerodes.exchangesync.exchange.ExchangeSourceImpl.getAllAppointments(ExchangeSourceImpl.java:399) at com.zerodes.exchangesync.sync.SyncCalendarsImpl.generatePairs(SyncCalendarsImpl.java:45) at com.zerodes.exchangesync.sync.SyncCalendarsImpl.syncAll(SyncCalendarsImpl.java:98) at com.zerodes.exchangesync.App.main(App.java:48) Caused by: java.lang.ClassNotFoundException: javax.xml.ws.http.HTTPException at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:583) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:178) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:521)
I’ve already figured out that I now need to install the jaxws-api Debian Package, which provides the missing classes in /usr/share/java/jaxws-api.jar . Which java command line do I need in order to include the classes from the installed jar file? I have already tried this, but I am getting the same error:
/usr/bin/java -cp /usr/share/java/jaxws-api.jar -jar exchange-sync.jar
BTW: I am a Java noob and I don’t want to mess with recompiling things. I am also sure that javax.xml.ws.http.HTTPException resides in jaxws-api.jar , as I have browsed that JAR file with vim and found that class in it.