Главная страница » Как собрать java проект в jar

Как собрать java проект в jar

  • автор:

Creating a JAR File

The basic format of the command for creating a JAR file is:

The options and arguments used in this command are:

  • The c option indicates that you want to create a JAR file.
  • The f option indicates that you want the output to go to a file rather than to stdout.
  • jar-file is the name that you want the resulting JAR file to have. You can use any filename for a JAR file. By convention, JAR filenames are given a .jar extension, though this is not required.
  • The input-file(s) argument is a space-separated list of one or more files that you want to include in your JAR file. The input-file(s) argument can contain the wildcard * symbol. If any of the "input-files" are directories, the contents of those directories are added to the JAR archive recursively.

The c and f options can appear in either order, but there must not be any space between them.

This command will generate a compressed JAR file and place it in the current directory. The command will also generate a default manifest file for the JAR archive.

The metadata in the JAR file, such as the entry names, comments, and contents of the manifest, must be encoded in UTF8.

You can add any of these additional options to the cf options of the basic command:

When you create a JAR file, the time of creation is stored in the JAR file. Therefore, even if the contents of the JAR file do not change, when you create a JAR file multiple times, the resulting files are not exactly identical. You should be aware of this when you are using JAR files in a build environment. It is recommended that you use versioning information in the manifest file, rather than creation time, to control versions of a JAR file. See the Setting Package Version Information section.

An Example

Let us look at an example. A simple TicTacToe applet. You can see the source code of this applet by downloading the JDK Demos and Samples bundle from Java SE Downloads. This demo contains class files, audio files, and images having this structure:

TicTacToe folder Hierarchy

The audio and images subdirectories contain sound files and GIF images used by the applet.

You can obtain all these files from jar/examples directory when you download the entire Tutorial online. To package this demo into a single JAR file named TicTacToe.jar, you would run this command from inside the TicTacToe directory:

The audio and images arguments represent directories, so the Jar tool will recursively place them and their contents in the JAR file. The generated JAR file TicTacToe.jar will be placed in the current directory. Because the command used the v option for verbose output, you would see something similar to this output when you run the command:

You can see from this output that the JAR file TicTacToe.jar is compressed. The Jar tool compresses files by default. You can turn off the compression feature by using the 0 (zero) option, so that the command would look like:

You might want to avoid compression, for example, to increase the speed with which a JAR file could be loaded by a browser. Uncompressed JAR files can generally be loaded more quickly than compressed files because the need to decompress the files during loading is eliminated. However, there is a tradeoff in that download time over a network may be longer for larger, uncompressed files.

The Jar tool will accept arguments that use the wildcard * symbol. As long as there weren't any unwanted files in the TicTacToe directory, you could have used this alternative command to construct the JAR file:

Though the verbose output doesn't indicate it, the Jar tool automatically adds a manifest file to the JAR archive with path name META-INF/MANIFEST.MF. See the Working with Manifest Files: The Basics section for information about manifest files.

In the above example, the files in the archive retained their relative path names and directory structure. The Jar tool provides the -C option that you can use to create a JAR file in which the relative paths of the archived files are not preserved. It's modeled after TAR's -C option.

As an example, suppose you wanted to put audio files and gif images used by the TicTacToe demo into a JAR file, and that you wanted all the files to be on the top level, with no directory hierarchy. You could accomplish that by issuing this command from the parent directory of the images and audio directories:

The -C images part of this command directs the Jar tool to go to the images directory, and the . following -C images directs the Jar tool to archive all the contents of that directory. The -C audio . part of the command then does the same with the audio directory. The resulting JAR file would have this table of contents:

By contrast, suppose that you used a command that did not employ the -C option:

Back to the basics of Java — Part 2: The JAR

In the first part I introduced a simple example explaining how to use the classpath correctly. I will use this example for this part as well, so if you did not create that yet you can copy it from the first part before proceeding if you want to follow along.

Back to the basics of Java — Part 1: Classpath

My favourite programming language has always been Java, coincidentally it was also my first language I ever used. If…

A jar file is simply a type of archive used to package java class files and associated resources for distribution. If we remember from the last article, our file structure was like this.

Let’s create an executable jar containing the class files. First we navigate to the root directory.

First attempt — the messy way

Then we run this command [1].

  • —create (or -c): create a new archive
  • —file (or -f): filename of the archive
  • file(s): the files to include in the archive

It seems like it cannot find a manifest. So let’s inspect what the contents are. Here are three commands that give you the exact same output so I will show all of them but will from now on use the last one.

  • —list (or -t): list the contents of a jar
  • —file (or -f): the jar file

It doesn’t look very good. Let’s find out what the manifest contains.

  • —extract (or -x): extract the content from a jar

Then print the manifest.

Is this fixable? Sure, I’ll quickly show the fix. The minimum fix is to update the manifest with a classpath.

  • —update (or -u): update a jar file
  • —manifest (or -m): manifest file to include information from

Let’s run it again.

Okey same problem because it is not an executable jar, there is no main class in the jar manifest. However, we can run it by specifying the jar in the classpath.

Let’s update our manifest file by adding a main class attribute and update the jar.

You can ignore this warning because if we inspect the MANIFEST.MF file as shown above you will see that it looks good.

But if you wanted, you could have overridden the manifest.txt file with just one new line containing the main-class attribute and it would be changed in the MANIFEST.MF file in the jar.

Alternatively, you can actually specify the main-class attribute on the command line to update the jar, which is a quick way of changing the attribute.

  • —main-class (or -e): changes the Main-Class attribute in the manifest

Now we can run it like normally.

Okey, so this was messy. Let’s try and simplify things. First, let’s clear the directory of the files to start over.

Second attempt —the simpler way

Now I’ll try to make this a bit more succinct.

  • -C: changes directory and includes the provided file (2 argument flag, note the space)

Let’s inspect the content.

Already here you can see that it looks a lot better, no bin directory anywhere. We should be able to run this directly.

Alright, great. However, we can actually simplify the command a little bit.

Here I specified the directory and a wildcard using the dot (.) which takes everything inside the bin directory.

Side note

The ordering of the arguments here is important. If you for instance did this instead:

The command would succeed, but you would end up with a file called myprogram.Main with a main class attribute of project.jar.

Library jar

For this part, I’m going to move out Util.class into its own jar file similarly to what I did in the first part of this series when explaining the classpath.

So the new file structure will look like this.

And we will run the following commands to generate our jar files.

Now if we try and run the project.jar we will obviously get an error because it cannot find the Util class.

So how do we run this? If we remember from the classpath article we can specify the jars on the classpath like this.

But what if we want to make project.jar an executable jar file so that the command that failed above works? Well, then we need to use the manifest like so.

Note that the Class-Path attribute is a relative path to the created jar file.

I hope this learning process-like article has helped your understanding of creating jars. Thanks for reading and please give me a like or comment if there is something incorrectly written or it can be improved in any way!

Packaging the Application

We can package the application into a Java ARchive file (JAR).

When the code is ready, we can package our application in a JAR. JAR files are often used to deploy an application to the production server. Once a JAR file has been built, it is called an artifact. Let's take look at how to create artifacts in IntelliJ IDEA.

Creating an Artifact

1) Press Cmd+; on macOS, or Shift+Control+Alt+S on Windows to bring up the Project Structure dialog.

2) Select Artifacts from the left-hand menu and then press the + icon. Select JAR and then From modules with dependencies.

Selecting a JAR file to build

You don't need to change anything for the Module, however you do need to say which class in your project has the main method. Click the browse button to navigate to your main method. IntelliJ IDEA will show you a list of classes in your project, you only have one so select that.

Main class selected for JAR

3) Press OK to select your class. All the other defaults are fine for this tutorial, press OK. Now you can see your new JAR file defined in the Project Structure dialog.

Hello World JAR in the Project Structure dialog

4) If it matches the above screenshot, press OK. You have now defined how to build the JAR file, but you haven't actually built it yet. You need to build it with your build artifacts.

5) Go to Build > Build Artifacts. You will only have one to choose from which is the one that we just defined.

Build artifacts

6) Press Enter to build the artifact. Your status bar at the bottom-left of the screen will show you when this has completed.

Status bar

IntelliJ IDEA puts the artifact in a new folder in your out folder called HelloWorld_jar .

Project window artifact

To make sure that this JAR file was created correctly you will want to run it. We'll do this in the next step of this tutorial by using a run configuration.

Компиляция в Java

Компиляция в Java - 1

Программирование в IDE — прекрасно: связанность зависимостей кода, удобный дебаг, понятное тестирование, темная тема. Так вот, благодаря IDE разработка развивается семимильными шагами. Но она расслабляет. С каждым днем, погружаясь в функционал IDE, разработчик привыкает к коммиту одной кнопкой или сборке двумя кликами. Гораздо хуже обстоит ситуация с новичками в программировании, которые с самого начала работают в IDE, игнорируя работу в командной строке. Например, в Intellij IDEA компиляция Java приложения демонстрируется загрузочным баром в нижней панели, а все параметры компиляции, обработка classpath и прочих прелестей Java-жизни остается за кадром. Предлагаем поговорить о компиляции в Java без IDE. Для запуска примеров в статье следует убедиться, что на вашей машине установлена JDK 1.7 и старше.

Как скомпилировать программу?

  1. Есть исходный код в файле с именем НазваниеКласса.java;
  2. Если в коде нет ошибок, он компилируется в байт-код (в файл НазваниеКласса.class);
  3. Программа запускается.

Для чего нужна команда javac

Компиляция в Java - 2

Окей, первый пункт выполнен. Идем дальше, чтобы понять: скомпилировать — это как? 🙂 В этом нам поможет команда javac, в аргументе которой необходимо указать нужный файл: Если нет ошибок в коде, рядом с файлом Test.java появится файл Test.class. Это и есть скомпилированный байт-код. Теперь его нужно запустить. Здесь используется команда java, запускающая байт-код: На скриншоте видно, что в выводе получаем какие-то иероглифы: очевидно, это сбитая кодировка. Как правило это происходит в системе Windows. Для корректного отображения кириллицы в консоли, есть следующие команды: Они меняют текущую кодовую страницу командной консоли на время работы текущего окна. Попробуем еще раз: Это говорит приложение из командной строки. Знать принцип работы команды javac очень полезно, так как эта команда лежит в основе любой системы сборки проектов.

Компиляция и выполнение нескольких классов

Создание JAR-файлов

Компиляция в Java без IDE: обзор систем сборок

Как скомпилировать Java?

  • mkdir — создание директорий
  • delete — удаление файлов и директорий
  • javac — компиляция Java–кода
  • java — запуск скомпилированного кода


Компиляция в Java - 3

Maven предлагает несколько другой подход к сборке проектов. Здесь разработчик скорее описывает свой проект и дополнительные инструменты, которые использует, в отличие от Ant, где сборка — это последовательность действий. Maven популярен среди разработчиков благодаря простому управлению зависимостями и удобной интеграции со всеми средами разработки. При работе с Maven придерживаются такой структуры проекта: Правила сборки, зависимости и прочее описывается в файле pom.xml. Как правило он находится в главной папке проекта. При запуске Maven проверяет структуру и синтаксис файла, предупреждая об ошибках. В главной директории рядом с папками bin и src создаем файл pom.xml, внутрь добавляем: Далее в командной строке выполняем команду mvn: Теперь в папке bin есть папка src, в которой находятся скомпилированные классы. В pom.xml в теге build определена цель сборки — компиляция, директории файлов исходного кода и результата компиляции, а также имя проекта. У Maven есть множество целей сборки и плагинов для запуска тестирования, создания Jar-файлов, сборки дистрибутивов и других задач.

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

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