Java run jar with libs

Creating Executable Jars

A .jar file can be used to distribute a Java program. A .jar file is essentially a .zip file that follows a specific structure. This page describes how to use IntelliJ to create a .jar file that can be executed from the command line.

Jar with JavaFX packages included (preferred)

If the computer intended to run the program does not have JavaFX installed on it, it is possible to bundle the JavaFX libraries in the .jar but it requires more steps and results in a larger file.

Configuring Jar to be Created

public class Launcher   public static void main(String[] args)  // Replace "Main" with the name of the class that extends Application // See https://stackoverflow.com/a/52654791/3956070 for explanation Main.main(args); > > 
  • Go to File ->Project Structure. ( CTRL + ALT + SHIFT + S )
  • Select Artifacts
  • Click +
  • Select JAR ->From modules with dependencies.
  • Select the class Launcher class
  • Click OK
  • Click the + below the Output Layout tab and select Directory Content
  • Select the C:\Program Files\Java\javafx-sdk-19\bin folder
  • Click OK twice

Creating the Jar

  • Go to Build ->Build Artifacts
  • Select the Build action in the pop-up menu
  • The .jar file should be located in a folder in the out\artifacts folder of your project

Running the Jar file

You should be able to run the .jar file on any Windows system with Java, but not necessarily JavaFX, installed. Move the .jar file to your project folder (same folder as the src and .iml file). Then use the following command (from the command line):

Jar without JavaFX packages

This approach requires that the computer on which the .jar is to be executed already has JavaFX installed and configured.

Configuring Jar to be Created

  • Go to File ->Project Structure. ( CTRL + ALT + SHIFT + S )
  • Select Artifacts
  • Click +
  • Select JAR ->From modules with dependencies.
  • Select the class that contains the main method (class that extends Application )
  • Click OK
  • In the Output Layout tab, remove all but the last item:
    • Select Extracted ‘javafx-swf.jar/‘ and click —
    • Remove the remaining entries that begin with Extracted leaving just one entry containing compiled output

    Creating the Jar

    • Go to Build ->Build Artifacts
    • Select the Build action in the pop-up menu
    • The .jar file should be located in a folder in the out\artifacts folder of your project

    Running the Jar file

    You should be able to run the .jar file on any Windows system with Java and JavaFX installed. Move the .jar file to your project folder (same folder as the src and .iml file). Then use the following command (from the command line):

    java —module-path C:\Java\javafx-sdk-19\lib —add-modules javafx.controls,javafx.fxml,javafx.swing -jar WHATEVER.jar 

    Of course, you’ll need to modify the module path to where you installed JavaFX.

    Источник

    Java Language The Java Command — ‘java’ and ‘javaw’ Running a Java application with library dependencies

    This is a continuation of the «main class» and «executable JAR» examples.

    Typical Java applications consist of an application-specific code, and various reusable library code that you have implemented or that has been implemented by third parties. The latter are commonly referred to as library dependencies, and are typically packaged as JAR files.

    Java is a dynamically bound language. When you run a Java application with library dependencies, the JVM needs to know where the dependencies are so that it can load classes as required. Broadly speaking, there are two ways to deal with this:

    • The application and its dependencies can be repackaged into a single JAR file that contains all of the required classes and resources.
    • The JVM can be told where to find the dependent JAR files via the runtime classpath.

    For an executable JAR file, the runtime classpath is specified by the «Class-Path» manifest attribute. (Editorial Note: This should be described in a separate Topic on the jar command.) Otherwise, the runtime classpath needs to be supplied using the -cp option or using the CLASSPATH environment variable.

    For example, suppose that we have a Java application in the «myApp.jar» file whose entry point class is com.example.MyApp . Suppose also that the application depends on library JAR files «lib/library1.jar» and «lib/library2.jar». We could launch the application using the java command as follows in a command line:

    $ # Alternative 1 (preferred) $ java -cp myApp.jar:lib/library1.jar:lib/library2.jar com.example.MyApp $ # Alternative 2 $ export CLASSPATH=myApp.jar:lib/library1.jar:lib/library2.jar $ java com.example.MyApp 

    (On Windows, you would use ; instead of : as the classpath separator, and you would set the (local) CLASSPATH variable using set rather than export .)

    While a Java developer would be comfortable with that, it is not «user friendly». So it is common practice to write a simple shell script (or Windows batch file) to hide the details that the user doesn’t need to know about. For example, if you put the following shell script into a file called «myApp», made it executable, and put it into a directory on the command search path:

    #!/bin/bash # The 'myApp' wrapper script export DIR=/usr/libexec/myApp export CLASSPATH=$DIR/myApp.jar:$DIR/lib/library1.jar:$DIR/lib/library2.jar java com.example.MyApp 

    then you could run it as follows:

    Any arguments on the command line will be passed to the Java application via the «$@» expansion. (You can do something similar with a Windows batch file, though the syntax is different.)

    pdf

    PDF — Download Java Language for free

    Источник

    Подключение библиотек в Java

    Библиотека — готовый набор классов и компонентов, который встраивают в программу, чтобы реализовать некий функционал. Например, в тысячах казуальных игр музыку можно проигрывать одним и тем же способом. Чтобы не тратить время на работу со звуком, программисту достаточно подключить подходящую библиотеку.

    Подключение Джава-библиотек в Eclipse

    Если вы пользуетесь средой разработки Eclipse, подключение библиотек в Java займёт у вас меньше минуты:

    • Разворачиваем дерево проекта в Package Explorer и находим папку libs. Если её нет — создаем.
    • Кладем нужный .jar в libs.
    • В появившемся окне выбираем «копирование файлов» (copy files) и жмём OK.
    • Обновляем проект: правый клик — «Refresh».

    Классы подключены и готовы к вызову из нашей программы.

    Подключение библиотек Java в Maven и Apache-Ant

    Минус подключения библиотек через IDE в том, что для пересборки проекта на другой машине нужна та же среда. Чтобы не зависеть от среды, используют системы сборки Maven и Ant.

    Чтобы «прикрутить» библиотеку к проекту Maven, нужно указать её среди зависимостей в файле pom.xml. С библиотекой может подтянуться еще несколько зависимостей, которые подключаются к этой библиотеке. В случае с jar этого не происходит.

    Как будет выглядеть наш pom.xml:

     xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0  ru.team.project  test-app  1.0   dependency>  Допустим, нам нужна Javassist для редактирования байткода. ----> org.javassist  javassist  3.21.0-GA    

    Теперь при компиляции проекта библиотека войдет в конечный .jar-файл.

    В Ant принцип схожий, но редактировать нужно файл build.xml. Путь к подключаемым библиотекам пишут с помощью тегов и . Сначала объясняем, где искать библиотеку:

    И далее передаём этот адрес тегу :

    Как подключить Java-библиотеку вручную

    Ваша IDE умеет подключать библиотеки, но как она это делает? Давайте посмотрим, что происходит на уровне файлов. Если библиотека написана на Джаве, её компоненты хранятся либо в архиве .jar, либо в исходниках .java. Более сложный вариант с интеграцией библиотек на C++ пока рассматривать не будем.

    Подключение jar-библиотек в Java

    Если на компьютере только одна версия Джавы — всё просто. Чтобы подключить .jar, достаточно положить его в папку lib директории Java на жестком диске. Виртуальная машина при ближайшем запуске сама возьмет код из библиотеки.

    Когда вы используете одновременно несколько версий Java-машины, раскладывать файлы библиотек для каждой из них утомительно. Лучше указать путь к нужным классам с помощью ключа -classpath.

    Открываем терминал и пишем:

    java -classpath ./classes ru.аuthor.libname.Main

    ru.аuthor.libname.Main — наша библиотека

    Точкой перед «/» отмечают текущую директорию.

    Можно перечислить несколько библиотек, код из которых компилятор соберет в порядке их перечисления:

    java -classpath ./classes;./lib/l1-0.1.jar;./lib/l2-1.5.jar ru. аuthor.libname.Main

    Теперь вы умеете подключать библиотеки даже в нестандартной ситуации: когда не установлена IDE или нужно скорректировать очередность подключения.

    Источник

    Читайте также:  Https edu rb ru pretorian login php вход
Оцените статью