Как создать jar файл в intellij idea
Как создать jar файл в intellij idea
Create your first Java application
In this tutorial, you will learn how to create, run, and package a simple Java application that prints Hello, World! to the system output. Along the way, you will get familiar with IntelliJ IDEA features for boosting your productivity as a developer: coding assistance and supplementary tools.
Watch the screencast and follow the step-by-step instructions below:
Prepare a project
Create a new Java project
In IntelliJ IDEA, a project helps you organize your source code, tests, libraries that you use, build instructions, and your personal settings in a single unit.
Launch IntelliJ IDEA.
In the New Project wizard, select New Project from the list on the left.
Name the project (for example HelloWorld ) and change the default location if necessary.
We’re not going to work with version control systems in this tutorial, so leave the Create Git repository option disabled.
To develop Java applications in IntelliJ IDEA, you need the Java SDK ( JDK ).
If the necessary JDK is already defined in IntelliJ IDEA, select it from the JDK list.
If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory (for example, /Library/Java/JavaVirtualMachines/jdk-17.0.2.jdk ).
After that, the IDE will create and load the new project for you.
Create a package and a class
Packages are used for grouping together classes that belong to the same category or provide similar functionality, for structuring and organizing large applications with hundreds of classes.
IntelliJ IDEA creates the com.example.helloworld package and the HelloWorld class.
Together with the file, IntelliJ IDEA has automatically generated some contents for your class. In this case, the IDE has inserted the package statement and the class declaration.
This is done by means of file templates. Depending on the type of the file that you create, the IDE inserts initial code and formatting that is expected to be in all files of that type. For more information on how to use and configure templates, refer to File templates.
The Project tool window Alt+1 displays the structure of your application and helps you browse the project.
In Java, there’s a naming convention that you should follow when you name packages and classes.
Write the code
Add the main() method using live templates
Type main and select the template that inserts the main() method declaration.
Live templates are code snippets that you can insert into your code. main is one of such snippets. Usually, live templates contain blocks of code that you use most often. Using them can save you some time as you don’t have to type the same code over and over again.
For more information on where to find predefined live templates and how to create your own, refer to Live templates.
Call the println() method using code completion
After the main() method declaration, IntelliJ IDEA automatically places the caret at the next line. Let’s call a method that prints some text to the standard system output.
Type Sy and select the System class from the list of code completion suggestions (it’s from the standard java.lang package).
Press Ctrl+. to insert the selection with a trailing comma.
IntelliJ IDEA shows you the types of parameters that can be used in the current context. This information is for your reference.
For information on different completion modes, refer to Code completion.
Call the println() method using a live template
You can call the println() method much quicker using the sout live template.
After the main() method declaration, IntelliJ IDEA automatically places the caret at the next line. Let’s call a method that prints some text to the standard system output.
Build and run the application
Valid Java classes can be compiled into bytecode. You can compile and run classes with the main() method right from the editor using the green arrow icon in the gutter.
Click in the gutter and select Run ‘HelloWorld.main()’ in the popup. The IDE starts compiling your code.
When the compilation is complete, the Run tool window opens at the bottom of the screen.
If your code is not correct, and the IDE can’t compile it, the Run tool window will display the corresponding exit code.
Once javac finishes compilation, it places the compiled bytecode to the out directory, which is highlighted with yellow in the Project tool window.
After that, the JVM runs the bytecode.
Automatically created run configurations are temporary, but you can modify and save them.
IntelliJ IDEA automatically analyzes the file that is currently opened in the editor and searches for different types of problems: from syntax errors to typos. The Inspections widget at the top-right corner of the editor allows you to quickly see all the detected problems and look at each problem in detail. For more information, refer to Current file.
Package the application in a JAR
Create an artifact configuration for the JAR
To the right of the Main Class field, click and select HelloWorld (com.example.helloworld) in the dialog that opens.
IntelliJ IDEA creates the artifact configuration and shows its settings in the right-hand part of the Project Structure dialog.
Apply the changes and close the dialog.
Build the JAR artifact
If you now look at the out/artifacts folder, you’ll find your JAR there.
Run the packaged application
To make sure that the JAR artifact is created correctly, you can run it.
Use Find Action Ctrl+Shift+A to search for actions and settings across the entire IDE.
Create a run configuration for the packaged application
To run a Java application packaged in a JAR, IntelliJ IDEA allows you to create a dedicated run configuration.
In the Path to JAR field, click and specify the path to the JAR file on your computer.
Doing this means that the HelloWorld.jar is built automatically every time you execute this run configuration.
Run configurations allow you to define how you want to run your application, with which arguments and options. You can have multiple run configurations for the same application, each with its own settings.
Execute the run configuration
On the toolbar, select the HelloWorldJar configuration and click to the right of the run configuration selector. Alternatively, press Shift+F10 if you prefer shortcuts.
As before, the Run tool window opens and shows you the application output.
The process has exited successfully, which means that the application is packaged correctly.
Compile and build applications with IntelliJ IDEA
The IntelliJ IDEA compilation and building process compiles source files and brings together external libraries, properties files, and configurations to produce a living application. IntelliJ IDEA uses a compiler that works according to the Java specification.
You can compile a single file, use the incremental build for a module or a project, and rebuild a project from scratch.
If you have a pure Java or a Kotlin project we recommend that you use IntelliJ IDEA to build your project since IntelliJ IDEA supports the incremental build which significantly speeds up the building process.
However, IntelliJ IDEA native builder might not correctly build the Gradle or Maven project if its build script file uses custom plugins or tasks. In this case, the build delegation to Gradle or Maven can help you build your project correctly.
Compile a single file or class
Open the needed file in the editor and from the main menu, select Build | Recompile ‘class name’ ( Ctrl+Shift+F9 ).
If errors occur during the compilation process, IntelliJ IDEA will display them in the Review compilation and build output along with warning messages.
Change the compilation output locations
Inside the output directory, IntelliJ IDEA also creates subdirectories for each of your modules.
The default paths for subdirectories are as follows:
At the project level, you can change the
/out part of the output path. If you do so (say, specify some instead of
At the module level, you can specify any desirable compilation output location for the module sources and tests individually.
Specify compilation output folders
Open the Project Structure dialog ( File | Project Structure Ctrl+Alt+Shift+S ).
Build
When you execute the Build command, IntelliJ IDEA compiles all the classes inside your build target and places them inside the output directory.
When you change any class inside the build target and then execute the build action, IntelliJ IDEA performs the incremental build that compiles only the changed classes. IntelliJ IDEA also recursively builds the classes’ dependencies.
Build a module, or a project
Select a module or a project you want to compile and from the main menu, select Build | Build Project ( Ctrl+F9 ).
IntelliJ IDEA displays the compilation results in the Review compilation and build output.
If you add a module dependency to your primary module and build the module, IntelliJ IDEA builds the dependent module as well and displays it in the output directory alongside the primary one. If the dependent module has its own module dependencies, then IntelliJ IDEA compiles all of them recursively starting with the least dependent module.
The way the module dependencies are ordered may be very important for the compilation to succeed. If any two JAR files contain classes with the same name, the IntelliJ IDEA compiler will use the classes from the first JAR file it locates in the classpath.
For more information, see Module dependencies.
Rebuild
When you execute a rebuild command, IntelliJ IDEA cleans out the entire output directory, deletes the build caches and builds a project, or a module from scratch. It might be helpful, when the classpath entries have changed. For example, SDKs or libraries that the project uses are added, removed or altered.
Rebuild a module, or a project
From the main menu, select Build | Rebuild Project for the entire project or Build | Rebuild ‘module name’ for the module rebuild.
IntelliJ IDEA displays the build results in the Review compilation and build output.
When the Rebuild Project action is delegated to Gradle or Maven, IntelliJ IDEA doesn’t include the clean task/goal when rebuilding a project. If you need, you can execute the clean command before the rebuild using the Execute Before Rebuild option in the Gradle or Maven tool window.
Background compilation (auto-build)
You can configure IntelliJ IDEA to build your project automatically, every time you make changes to it. The results of the background compilation are displayed in the Problems tool window.
Configure the background compilation
Now when you make changes in the class files, IntelliJ IDEA automatically performs the incremental build of the project.
The automatic build also gets triggered when you save the file ( Ctrl+S ) or when you have the Save files automatically if application is idle for N sec. option selected in the System settings dialog.
Enabling the Build project automatically option also enables Build project in Settings/Preferences | Tools | Actions on Save
When you have the Power Save Mode option ( File | Power Save Mode ) enabled in your project, the auto-build action is disabled, and you need to manually run the build ( Ctrl+F9 ).
Compile before running
By default, when you run an application, IntelliJ IDEA compiles the module where the classes you are trying to run are located.
If you want to change that behavior, you can do so in the Run/Debug Configurations dialog.
Configure a run/debug configuration
In the dialog that opens, create a new or open an existing run configuration.
Click the Modify options link.
If you need to add a new configuration action, click and from the list that opens, select the desired option.
For example, if you select Build Project then IntelliJ IDEA will build the whole project before the run. In this case, the dependencies that were not included in the build with the Build action, will be accounted for. If you select the Build, no error check option, IntelliJ IDEA will run the application even if there are errors in the compilation results.
Review compilation and build output
IntelliJ IDEA reports compilation and building results in the Build tool window, which displays messages about errors and warnings as well as successful steps of compilation.
If you configured an auto-build, then IntelliJ IDEA uses the Problems tool window for messages. The window is available even if the build was executed successfully. To open it, click Auto-build on the status bar.
Double-click a message to jump to the problem in the source code. If you need to adjust the compiler settings, click .
Package an application into a JAR
Create an artifact configuration for the JAR
To the right of the Main Class field, click and select the main class in the dialog that opens (for example, HelloWorld (com.example.helloworld) ).
IntelliJ IDEA creates the artifact configuration and shows its settings in the right-hand part of the Project Structure dialog.
Apply the changes and close the dialog.
Build the JAR artifact
When you’re building a project, resources stored in the Resources root are copied into the compilation output folder by default. If necessary, you can specify another directory within the output folder to place resources.
Run a packaged JAR
To run a Java application packaged in a JAR, IntelliJ IDEA allows you to create a dedicated run configuration.
If you have a Gradle project, use Gradle to create and run the JAR file.
For Maven projects, you can use IntelliJ IDEA to run the JAR file. If you have a Spring Boot Maven project, refer to the Spring section.
Create a run configuration
Add a name for the new configuration.
In the Path to JAR field, click and specify the path to the JAR file on your computer.
Doing this means that the JAR is built automatically every time you execute the run configuration.
Run configurations allow you to define how you want to run your application, with which arguments and options. You can have multiple run configurations for the same application, each with its own settings.
Execute the run configuration
On the toolbar, select the created configuration and click to the right of the run configuration selector. Alternatively, press Shift+F10 if you prefer shortcuts.
As before, the Run tool window opens and shows you the application output.
If the process has exited successfully, then the application is packaged correctly.
Незаменимая для программистов — IntelliJ IDEA
Есть множество сред разработки программного обеспечения: Visual Studio, Eclipse, Android Studio, Xamarin Studio и т.д. Все они имею свои плюсы и минусы и предназначены для разных языков программирования и целей.
IntelliJ IDEA — интегрированная среда разработки программного обеспечения, разработанная компанией JetBrains в 2001 году. Она поддерживается на таких операционных системах как: Windows, Linux, macOS. Эта среда разработки поддерживает многие современные высокоуровневые языки программирования, такие как:
Начиная с версии 9.0, среда доступна в двух редакциях: Community Edition и Ultimate Edition. Community Edition — это полностью свободная версия, доступная под лицензией Apache 2.0, в ней реализована полная поддержка Java SE, Kotlin, Groovy, Scala, а также интеграция с наиболее популярными системами управления версиями.
Ultimate Edition доступна под коммерческой лицензией (платная версия). В ней реализована поддержка Java EE, UML-диаграмм, подсчёт покрытия кода, а также поддержка других систем управления версиями, языков и фреймворков.
Как пользоваться
Первоначальная настройка при первом запуске
При первом запускаете или после того, как было сделано обновление программы, откроется диалоговое окно полной установки, в котором вы можете выбрать импортирование параметров IDE.
Если это был первая установка, то выбирается параметр «Не импортировать параметры» так как их неоткуда импортировать. Далее можно выбрать тему среды.
После выбора темы, можно выбрать выключить или включить нужные плагины, загрузить и установить их из репозитория плагинов IntelliJ IDEA.
После завершения первоначальной настройки, отобразится экран приветствия. Он позволяет:
После запуска, среда разработки открывает справку Trip of Day.
Как создать проект java
package com.company;
public class Main <
public static void main(String[] args) <
// write your code here
>
>
По завершению выполнения компилятор выдает нам следующее:
Process finished with exit code 0
Запустить проект
Что бы запустить проект в IntelliJ IDEA можно воспользоваться знаком старта на верхней панели быстрого доступа:
Как создать jar файл?
Для создания jar файла необходимо открыть окно Project Structure (значок в верхнем меню быстрого доступа рядом с лупой). Так же это окно можно найти и открыть через поиск (лупа на панели быстрого доступа) или сочетание клавиш Ctrl+Alt+Shift+S.
В открывшемся окне в поле Main Class выбираем главный класс проекта и нажимаем OK.
В следующем окне ничего не делаем, просто нажимаем ОК.
В открывшемся окне выбираем созданный jar файл и нажимаем OK.
Теперь в панели где отображается структура проекта появляется папка out в которой можно найти созданный jar файл
Все тоже самое только на видео:
Увеличение шрифта
Смена темы
Помимо этого, через знак колеса (настройки) можно импортировать желаемую тему или цвет фона.
Создание библиотеки
Jar файл является библиотекой для языка java (пакетом, в котором собраны классы). Как создается Jar файл было описано в четвертом пункте.
Полезное видео по настройке и запуску
Загрузка, установка и настройка. Первая программа на Java — Hello java!
Покупка и актуальная цена
Где скачать и как установить?
На Windows
На macOS
На Linux
Установка на ubuntu индетичная.
ВАЖНО: перед установкой убедитесь, что на компьютере, на который устанавливается среда разработки уже установлена Java машина.
Обновление
После этого открывается диалоговое окно, в котором написана текущая версия среды разработки и последняя ее версия. Для обновления версии нажимаем кнопку Download. Откроется браузер со страницей откуда можно скачать последнюю версию.
Системные требования
Требования к оборудованию:
Горячие клавиши
Редактирование и генерация кода
Ctrl + Space | Показывает список вариантов которым можно завершить ввод |
Ctrl + Shift + Space | Тоже самое, что и Ctrl + Space, только учитывает статические поля и методы. Также помогает инициализировать поле подходящим типом. |
Ctrl + Shift + Enter | Завершение оператора, ставит в конце оператора точку запятую |
Ctrl + P | Сведения о параметрах (в пределах аргументов вызываемого метода) |
Ctrl + Q | Быстрый поиск документации |
Shift + F1 | Внешняя документация |
Ctrl + наведение курсором на команду | Краткая информация |
Alt + Insert | Генерация блоков кода (Getters, Setters, Constructors, hashCode/equals, toString) |
Ctrl + O | Переопределение метода |
Ctrl + I | Реализация методов |
Ctrl + Alt + T | Оборачивает выделенную команду в блок кода (if..else, try..catch, for, synchronized, etc.) |
Ctrl + / | Однострочное комментирование / раскомментирование |
Ctrl + Shift + / | Многострочное комментирование / раскомментирование |
Ctrl + W | Умное выделение текста. Эта команда выделяет сначала слово где стоит курсор, потом строку (или целый блок кода) |
Alt + Q | Контекстная информация |
Alt + Enter | Показать предлагаемое исправление |
Ctrl + Alt + L | Структурирование кода (это сочетание делает код читабельным и удобным для восприятия) |
Ctrl + Alt + O | Удаление неиспользуемых импортов |
Ctrl + Alt + I | Авто-отступ линии |
Tab / Shift + Tab | Отступ / удаление отступа выбранному фрагменту кода |
Ctrl + Shift + V | Вставить последний фрагмент кода из буфера обмена |
Ctrl + D | Дублирование текущей строки |
Ctrl + Y | Удаляет целую строку |
Ctrl + Shift + J | Объединение строк |
Ctrl + Enter | Разделение строки (отличается от простое Enter тем, что курсор остается на месте) |
Ctrl + Shift + U | Переключает слово на котором стоит курсор в нижний / верхний регистр |
Ctrl + Shift + ] / [ | Выделить код до конца / начала блока |
Ctrl + Delete | Удалить слово после курсора |
Ctrl + Backspace | Удалить слово перед курсором |
Ctrl + NumPad+/- | Развернуть / свернуть блок кода |
Ctrl + Shift + NumPad+ | Развернуть все |
Ctrl + Shift + NumPad- | Свернуть все |
Ctrl + F4 | Закрыть активное окно редактора |
Поиск / замена в коде
Ctrl + F | Поиск по коду в текущей вкладке |
F3 | Поиск вперед |
Shift + F3 | Поиск назад |
Ctrl + R | Замена найденного слова |
Ctrl + Shift + F | Искать по проекту |
Ctrl + Shift + R | Заменить по проекту |
Ctrl + Shift + S | Поиск по шаблону |
Ctrl + Shift + M | Замена по шаблону |
Поиск использованного кода
Alt + F7 / Ctrl + F7 | Найти использования / Найти использования в файле |
Ctrl + Shift + F7 | Выделить используемое в файле |
Ctrl + Alt + F7 | Показать использования метода, класса, переменной |
Компиляция/выполнение/отладка
F7 | Шаг при отладке |
F8 | Шаг обхода при отладке |
Shift + F7 | «Умный» шаг |
Shift + F8 | Выход из режима debug |
Alt + F9 | Запуск на выполнение до курсора |
Alt + F8 | Вычисление выражения |
Ctrl + F8 | Переключить точку остановки |
Ctrl + Shift + F8 | Показать точки остановки |
Ctrl + F9 | Структурирование проекта и сборка измененных файлов |
Ctrl + Shift + F9 | Компиляция выбранного файла пакета или модуля |
Alt + Shift + F10 | Выбрать конфигурацию и запустить |
Alt + Shift + F9 | Выбрать конфигурацию и запустить в debug режиме |
Shift + F10 | Запуск на выполнение |
Shift + F9 | Запуск в debug режиме |
Ctrl + Shift + F10 | Выполнение в контексте конфигурации из редактора |
Навигация
Ctrl + N | Переход к классу (открывается поле для ввода класса к которому нужно перейти) |
Ctrl + Shift + N | Переход к файлу |
Ctrl + Alt + Shift + N | Переход к символу |
Alt + Right/Left | Переход к следующей / предыдущей вкладки редактора |
F12 | Вернуться к предыдущему окну инструмента |
Esc | Перейти к редактору (выход из текущего окна настроек) |
Shift + Esc | Скрыть активное или последнее активное окно |
Ctrl + Shift + F4 | Закрывает окно навигации по проекту |
Ctrl + G | Переход к строке по ее номеру |
Ctrl + E | Последние файлы |
Ctrl + Alt + Left/Right | Выделение текста по слову влево/вправо |
Ctrl + Shift + Backspace | Перейти в последнее место Редактора |
Alt + F1 | Выберите текущий файл или символ в любом режиме |
Ctrl + B | Перейти к объявлению поля, метода или класса |
Ctrl + Alt + B | Перейти к реализации (переходит во вкладку класса, где реализован используемый метод) |
Ctrl + Shift + I | Открыть быстрый доступ к реализации метода/класса |
Ctrl + Shift + B | Перейти к объявлению типа |
Ctrl + U | Перейти к супер методу или классу |
Alt + Up/Down | Переход к предыдущему / следующему методу |
Ctrl + ] / [ | Перейти в конец / начало блока |
Ctrl + F12 | Файловая структура |
Ctrl + H | Иерархии типа |
Ctrl + Shift + H | Иерархия метода |
Ctrl + Alt + H | Иерархии вызовов |
Alt + Home | Показать панель навигации |
F11 | Переключить закладку |
Ctrl + #2 | Перейти к номером закладки |
Shift + F11 | Показать закладки |
Рефакторинг (улучшение кода)
F5 | Копирование класса |
F6 | Переместить |
Alt + Delete | Безопасное удаление |
Shift + F6 | переименовывает поле, метод или класс во всех местах, где используется |
Ctrl + F6 | Изменить сигнатуру |
Ctrl + Alt + N | Встроить |
Ctrl + Alt + M | Поместить в метод |
Ctrl + Alt + V | Поместить в переменную |
Ctrl + Alt + F | Поместить в поле |
Ctrl + Alt + C | Поместить в константу |
Ctrl + Alt + P | Поместить в параметр |
Система управления версиями (Version Control System)
Ctrl + K | Commit (сохранение, фиксация) проекта в репозиторий |
Ctrl + | Обновить проект из репозитория |
Alt + Shift + C | Посмотреть последние изменения |
Работа с интерфейсом IDE
Alt + #9 | Открыть соответствующее окно инструмента |
Ctrl + S | Сохранить проект |
Ctrl + Alt + Y | Cинхронизировать |
Ctrl + Alt + F11 | Переключение полноэкранного режима |
Ctrl + Shift + F12 | Переключить максимизацию редактору |
Alt + Shift + F | Добавить в избранное |
Alt + Shift + I | Проверьте текущий файл с текущим профилем |
Ctrl + BackQuote (`) | Быстрое переключение текущей схемы |
Ctrl + Shift + A | Найти Действие |
Ctrl + Tab | Переключение между вкладками и окна инструментов |
Открытие окон настроек кода и среды разработки
Ctrl + Alt + S | Открытые окна Параметры (Settings) |
Ctrl + Alt + Shift + S | Открыть диалоговое Структура проекта (Project Structure) |
В данной статье были разобраны основные принципы работы со средой IntelliJ IDEA. У нее достаточно интуитивный интерфейс для пользователя. В ней можно создавать полноценные приложения на таких языках как Java, Python, Kotlin, Scala и т.д.
How to build jars from IntelliJ properly?
I have a project that contains a single module, and some dependencies. I’d like to create a jar, in a separate directory, that contains the compiled module. In addition, I’d like to have the dependencies present beside my module.
No matter how I twist IntelliJ’s «build jar» process, the output of my module appears empty (besides a META-INF file).
23 Answers 23
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Select a Main Class (the one with main() method) if you need to make the jar runnable.
The above sets the «skeleton» to where the jar will be saved to. To actually build and save it do the following:
Extract to the target Jar
Build | Build Artifact | Build
ProjectName | out | artifacts | ProjectName_jar | ProjectName.jar
This is still an issue in 2017, I hope it will help somebody out there! I found 2 possibilities to create working jar-s under IntelliJ 2017.2
1. Creating artifact from IntelliJ:
You have to change manifest directory:
replace «java» with «resources»
This is how it should look like:
Then you choose the dependencies what you want to be packed IN your jar, or NEAR your jar file
To build your artifact go to build artifacts and choose «rebuild». It will create an «out» folder with your jar file and its dependencies.
2. Using maven-assembly-plugin
Add build section to the pom file
This procedure will create the jar file under the «target» folder
I recently had this problem and think these steps are easy to follow if any prior solution or link is missing detail.
For those that benefit from images as I do:
Here are 2 examples with maven project, step by step:
Method 1: Build jar with maven and pom.xml
at pom.xml, add maven-jar-plugin.
screen capture: 4. open maven project box by click on the search icon and type maven,
click on clean, then click on install
your jar file will show up inside the target folder
Method 2: Build jar with maven without pom.xml change
Very important!
The MANIFEST.MF needs to be in your resources folder and the Main.Class needs to refer to
When i use these solution this error coming:
no main manifest attribute, in xxxxx.jar
and solution is:
You have to change manifest directory:
change java to resources
I was trying to build a jar from a multi-module Kotlin app and was getting the notorious ‘no main manifest attribute’ error. Creating the manifest directory in src/main/resources didn’t work either.
As the people above says, but I have to note one point. You have to check the checkbox:
With Maven you can use this plugin:
Jar is ok, since there is compiled output in ‘output’ directory (project/out/production//)
I guess, you have to run ‘make’ before building jar
for dependencies just check «show library» and choose what you want.
Here is the official answer of IntelliJ IDEA 2018.3 Help. I tried and It worked.
To build a JAR file from a module;
On the main menu, choose Build | Build Artifact.
From the drop-down list, select the desired artifact of the type JAR. The list shows all the artifacts configured for the current project. To have all the configured artifacts built, choose the Build all artifacts option.
This solution worked for me (special thanks to Thilina Ashen Gamage (see above) for tip):
Как правильно создавать jar-файлы из IntelliJ?
У меня есть проект, содержащий один модуль и некоторые зависимости. Я хочу создать банку в отдельном каталоге, содержащую скомпилированный модуль. Кроме того, я хотел бы, чтобы рядом с моим модулем присутствовали зависимости.
Как бы я ни крутил процесс сборки IntelliJ, вывод моего модуля кажется пустым (кроме файла META-INF).
задан 04 июля ’09, 14:07
21 ответы
Вышеупомянутое устанавливает «каркас», в который будет сохранена банка. Чтобы создать и сохранить его, сделайте следующее:
Извлечь в целевую банку
Сборка | Построить артефакт | Строить
ProjectName | из | артефакты | ProjectName_jar | ProjectName.jar
ответ дан 05 мар ’20, в 20:03
Это все еще проблема в 2017 году, надеюсь, это кому-нибудь поможет! Я нашел 2 возможности для создания рабочих jar-ов в IntelliJ 2017.2
1. Создание артефакта из IntelliJ:
Вам необходимо изменить каталог манифеста:
замените «java» на «ресурсы»
Вот как это должно выглядеть:
Затем вы выбираете зависимости, которые вы хотите упаковать в свою банку, или РЯДОМ с вашим файлом jar.
Чтобы построить свой артефакт, перейдите к созданию артефактов и выберите «Восстановить». Он создаст «выходную» папку с вашим файлом jar и его зависимостями.
2. Использование maven-assembly-plugin
Добавить раздел сборки в файл pom
Эта процедура создаст файл jar в «целевой» папке.
У меня недавно возникла эта проблема, и я думаю, что эти шаги легко выполнить, если в каком-либо предыдущем решении или ссылке отсутствуют детали.
ответ дан 19 дек ’15, 17:12
Для тех, кому изображения нравятся так же, как и мне:
ответ дан 05 мар ’20, в 20:03
Вот 2 примера с проектом maven, шаг за шагом:
Метод 1. Создайте jar с maven и pom.xml
в pom.xml добавьте maven-jar-plugin.
скриншот: 4. откройте окно проекта maven, щелкнув значок поиска и введите maven,
нажмите «Очистить», затем нажмите «Установить»
ваш файл jar появится внутри целевой папки
Метод 2: создать jar с maven без изменения pom.xml
Очень важный!
MANIFEST.MF должен находиться в папке ресурсов, а Main.Class должен ссылаться на
ответ дан 05 мар ’20, в 20:03
Когда я использую это решение эта ошибка:
нет основного атрибута манифеста в xxxxx.jar
и решение:
Вам необходимо изменить каталог манифеста:
изменить Java на ресурсы
Я пытался построить банку из многомодульный Котлин app и получал пресловутую ошибку «нет основного атрибута манифеста». Создание каталога манифеста в src/main/resources тоже не сработало.
С Maven вы можете использовать этот плагин:
ответ дан 07 мар ’17, в 09:03
Как сказано выше, но я должен отметить один момент. Вы должны поставить галочку в чекбоксе:
Jar в порядке, так как скомпилированный вывод находится в каталоге ‘output’ (project / out / production //)
Я думаю, вам нужно запустить make, прежде чем строить банку
для зависимостей просто отметьте «показать библиотеку» и выберите то, что вы хотите.
Создан 04 июля ’09, 22:07
Возможно, вы захотите взглянуть на Maven (http://maven.apache.org). Вы можете использовать его либо как основной процесс сборки для вашего приложения, либо просто для выполнения определенных задач в диалоговом окне «Редактировать конфигурации». Процесс создания JAR модуля в Maven довольно тривиален, если вы хотите, чтобы он включал все зависимости в самоисполняемый JAR, который также является тривиальным.
Если вы никогда раньше не использовали Maven, тогда вам стоит прочитать Лучшие сборки с Maven.
ответ дан 30 окт ’14, 09:10
Если вы используете сторонние библиотеки со своим проектом или если у вас есть проблемы с созданием файла MANIFEST.MF должным образом, могут возникнуть конфликты при запуске файлов JAR, созданных с использованием
упомянутый выше метод.
Вместо этого я предлагаю вам создать пустой JAR и вручную добавить все остальные элементы в выходной корень. Замечательную статью об этом методе можно найти здесь: http://karthicraghupathi.com/2016/07/10/creating-an-executable-jar-in-intellij-idea/ Я попробовал шаги, упомянутые там, и у меня все сработало!
Некоторые другие ответы бесполезны, потому что как только вы повторно импортируете проект IntelliJ IDEA из проекта maven, все изменения будут потеряны.
Создание jar-файла должно запускаться конфигурацией запуска / отладки, а не настройками проекта.
У Jetbrains есть хорошее описание того, как вы можете этого добиться:
Прокрутите вниз до раздела «Настройка триггеров для целей Maven».
(Единственным недостатком их описания является то, что их скриншоты имеют стандартную цветовую схему «черный на белом», а не супер-классную тему даркулы. Ух!)
ответ дан 25 мар ’18, в 18:03
Если вы пытаетесь создать банку с котлином, вам нужно создать src/main/java папку и используйте эту папку как место для папки META-INF.
Создан 07 июля ’18, 14:07
Вот официальный ответ Справка по IntelliJ IDEA 2018.3. Я попробовал, и это сработало.
Чтобы построить файл JAR из модуля;
В главном меню выберите Build | Постройте артефакт.
В раскрывающемся списке выберите нужный артефакт типа JAR. В списке показаны все артефакты, настроенные для текущего проекта. Чтобы создать все настроенные артефакты, выберите параметр «Создать все артефакты».
Это решение сработало для меня (особая благодарность Thilina Ashen Gamage (см. Выше) за совет):
ответ дан 04 мар ’19, в 23:03
Если вы читаете этот ответ, потому что столкнулись с ошибкой «файл ресурсов не найден», попробуйте следующее:
Создан 22 июля ’20, 12:07
Если вы работаете над проектом spring / mvn, вы можете использовать эту команду:
Файл jar будет сохранен в целевом каталоге.
ответ дан 23 окт ’18, 19:10
Широко используются Ant и Maven. Я предпочитаю Ant, я считаю, что он более легкий, и вы, разработчик, больше контролируете его. Кто-то может предположить, что это его обратная сторона 🙂
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками java intellij-idea jar build-process or задайте свой вопрос.
Как создать jar файл в intellij idea
Бывалый
Профиль
Группа: Участник
Сообщений: 248
Регистрация: 1.10.2008
Репутация: нет
Всего: нет
Эксперт
Профиль
Группа: Участник
Сообщений: 1168
Регистрация: 17.10.2008
Где: Санкт-Петербург
Репутация: 4
Всего: 75
Бывалый
Профиль
Группа: Участник
Сообщений: 248
Регистрация: 1.10.2008
Репутация: нет
Всего: нет
Спасибо.
А что указывать в пункте 3. CLASSPATH?
[Добавлено]
Это зависимые библиотеки, используемые в программе.
Если их нет можно оставить данное поле пустым?
И что такое PROFIT?
Эксперт
Профиль
Группа: Участник
Сообщений: 1168
Регистрация: 17.10.2008
Где: Санкт-Петербург
Репутация: 4
Всего: 75
Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux.
[ Время генерации скрипта: 0.1155 ] [ Использовано запросов: 21 ] [ GZIP включён ] How to Export a JAR from IntelliJA JAR (Java archive) file is a platform-independent package of your application in a single archive file. Packaging your application into a JAR makes it easier to distribute your program, and it also means functionalities in your program are reusable—for example, other programs can use your functionalities just by adding your JAR file as a dependency. There are two types of JARs: normal and executable. Normal JARs have no entry point, meaning you cannot directly execute this type of JAR. You can only add it as a dependency to other programs and access the classes and functions in your program. On the other hand, an executable JAR can be executed directly without any external program. Simply put, you can start an executable JAR directly just by double-clicking on it. IntelliJ provides a couple different ways to export a JAR from your workspace. In this tutorial, I’ll explain the two different methods for setting up your project architecture to export a JAR from IntelliJ: To understand the tutorial better, you’ll use a simple example program that accepts user profile information as a command line argument. This program also uses Picocli and Apache Commons Cli as external dependencies, which will support validating and parsing the command line parameters. Export a JAR Using the Build Artifact MethodIn this method, you’ll export a JAR using the IntelliJ build option. Before starting up, you’ll need to create a project and add the necessary dependencies to it. Dependencies are external programs packaged as a JAR with some functionalities implemented already and can easily be reused in your program. You’ll also need to create a main class with some simple functionality. Once you’ve created a project and a Run Configuration, which can be used to execute the project, let’s set up your program to export a JAR from the IntelliJ workspace. 1. Configure the project settings to define the artifacts of this project. Click Project Structure from the file menu. 2. In the Project Structure window, click Artifacts in the left pane, then click the plus symbol. Expand the JAR option and click From module with dependencies. This opens the Create JAR from Modules window. 3. Click the folder icon on the right side of the Main Class field to select the main class of your project. If you know the name of the main class, start typing in the field to see suggestions. 4. Set how external libraries should be handled while creating the JAR. There are two options: 5. Select the appropriate option and click OK, creating an artifact in your Artifacts window. You’ll see the name of the JAR in the Name field and its location in the Output directory. You can change the output directory to your desired location. If you need a JAR to be created during each and every project build, select Include in project build. If you don’t need that, leave the option unselected. In that case, you can build the JAR when you’re done with your project development, using the Build Artifacts option. When you click Build Artifacts, the JAR is generated in the output directory you’ve selected. So that’s how you export a JAR using the options available in IntelliJ. Next, you’ll see how to export a JAR using Maven. Exporting a JAR Using MavenMaven is a project management and automation tool, developed to make the build process easier. For example, you can create scripts to: To begin, create a Maven project in IntelliJ using this tutorial. Remember to add the necessary classes for your project. You can use the same class files and dependencies used in the previous section’s example. When you create a new Maven project, you’ll have the minimal POM file created in your project directory with the following contents: This POM file contains three important artifacts for the project: Configuring the Maven buildIn this section, you’ll configure the aspects of your Maven build. You can add various plugins inside the build section of your POM file based on your requirements. Each will have different functions. These plugins will be executed during the build of your project. In this tutorial, you’ll add the necessary plugin and configure it to export a JAR during the build. This adds a Maven compiler for your projects and also denotes the java version for compiling your sources. Here, you’re using Java version 1.8. For a quick explanation of the plugin’s various sections: Now that you’ve configured the Maven settings for your project, the whole POM file for the project should look like this: Executing a Maven BuildNext, you’ll create a configuration for the Maven build and execute it. It’ll export a JAR in the directories you’ve specified. 1. Navigate to Run > Edit Configurations. The Run/Debug Configurations window opens. 2. Select the Maven option from the Add New Configuration menu. This will create a Maven run configuration for you as below. 3. Give the configuration a name and add the project’s home directory as your home directory. 5. Click Apply and OK. This creates a run configuration for you directly. 6. From the Run menu, click Run configuration_name. Remember, since this project has the configurations in a Pom.xml file, you can also configure an automatic build using Jenkins scripts on any trigger (for example, after every commit to your git repo). ConclusionBuilding a JAR in IntelliJ is a little complicated when it comes to configuring project structure and generating artifacts. In the case of using Maven, it’s even more difficult due to the setup involved with configuring the POM file and the project’s build processes. But in this tutorial, you learned how to tackle two different options for building a JAR (using the build artifact method and using Maven) in IntelliJ to make the process easier. If you’ve got any suggestions or tips for creating a JAR that this article didn’t cover, please let me know about them in the comments. Как проводится компиляция в IntelliJ IDEAДата публикации: 2019-01-30 От автора: если бы не было таких мощных и качественных инструментов, как IntelliJ IDEA, компиляция занимала бы слишком много времени у разработчика — ведь это нужно собрать все файлы в единую программу, а после корректно запустить ее. К счастью, благодаря высокоразвитым IDE вся сложность заключается в настройке компилятора, а не каждого отдельного файла, поэтому в процессе работы с IntelliJ IDEA компиляция делается очень просто. Сегодня мы расскажем, как конфигурировать эту IDE для успешной сборки. Знакомство с компиляторомКомпиляция — это своеобразный процесс сборки, который заключается в трансляции всех модулей, которыми оснащена программа. В зависимости от ситуации, исходный код может быть написан на одном языке или на нескольких. Суть в том, чтобы преобразовать человекопонятный код в машинопонятный. До того, как появились компиляторы, все, с чем вы сталкиваетесь сегодня, делалось вручную. Но по мере развития продуктов данный софт стал необходим. Это программы, которые могут переводить код, написанный на высокоуровневом языке программирования, в низкоуровневый код, то есть в нули и единицы. Таким образом, процессор может понять то, что сказал человек. Компиляторы бывают нескольких видов. Точно так же и процесс компиляции бывает разным. Все зависит от того, какой язык используется (компилируемый/интерпретируемый) и какое применяется программное обеспечение для взаимодействия. Кстати, раньше этот вид ПО называли «программирующими программами». Этимологическая логика здесь проста: это был инструмент, который заставлял компьютер выполнять код — то есть, программировал его. JavaScript. Быстрый старт Изучите основы JavaScript на практическом примере по созданию веб-приложения Исполнительные файлыВы привыкли к тому, что готовая программа должна запуститься на вашем компьютере. И потому хотите, чтобы это происходило на каждом удобном вам ПК. И они так могут. Главное, чтобы на ПК или любом другом устройстве была установлена исполнительная среда Java. Она встречается не только на компьютерах, но и на всех остальных системах, вроде бытовой техники. Настройка проще, чем кажетсяВы можете изменить список распознанных ресурсов, исключить определенные пути из компиляции, выбрать нужный компилятор, настроить обработку аннотаций и т. д. В диалоговом окне «Settings/Preferences» выберите Build, Execution, Deployment. На странице компилятора вы можете, например, изменить регулярное выражение, описывающее расширения файлов, которые будут распознаваться как ресурсы. Используйте точки с запятой (;) для разделения отдельных шаблонов. На странице «Исключения» укажите файлы и папки, которые не следует включать в компиляцию. Используйте «+» для добавления элементов в список. Замечания:На странице Java Compiler проверьте, является ли используемый компилятор тем, который вам нужен. При необходимости выберите другой компилятор. На странице Annotation Processors настройте параметры обработки аннотаций. Примените изменения и закройте диалог. На этом заканчиваем рассказ о компиляции. Вам нужно запомнить два основных тезиса: компилятор IDEA нуждается в настройке, компиляции jar в exe не существует. Это совершенно другой, абсурдный процесс. И это не просто балластное знание. Оно убережет вас от скачивания утилит, которые обещают подобное чудо. JavaScript. Быстрый старт Изучите основы JavaScript на практическом примере по созданию веб-приложения Разработка веб-приложения на PHPСкачайте видеокурс и узнайте, как создать веб-приложение на PHP Creating the package and classUse IntelliJ IDEA to create a new package and class. We recommend putting IntelliJ IDEA into full screen to give you the maximum amount of space for your new Hello World project. The project window shows all the directories and the files that make up our projects. Of course, you can use the mouse to navigate the Project window, but you can also use the arrow keys. You can also toggle the display of this tool window with Cmd+ 1 on macOS, or Alt+ 1 on Windows/Linux. Creating Your Package and ClassNext, you’re going to create the package and the class. Application packages are used to group together classes that belong to the same category or provide similar functionality. They are useful for organising large applications that might have hundreds of classes. 1) To create a new class, select the blue src folder and press Cmd+ N on macOS, or Alt+ Insert on Windows/Linux. Select Java Class from the popup. Here, example might be your preferred domain and HelloWorld is the name of your Java class that IntelliJ IDEA will create. When you press Enter IntelliJ IDEA will create the package you wanted, and the correct directory structure for this package that you specified. It has also created a new HelloWorld.java file and generated the basic contents of this class file. For example, the package statement and class declaration, the class has the same name as the file. Coding Your HelloWorld Class1) You can move on to the next line in a class file by pressing Shift+ Enter. This moves the caret to the next line in the correct position and won’t break the previous line. Note: Pressing Escape will always close a drop-down or dialogue without making any changes. 3) Press Enter to select it. IntelliJ IDEA will generate the rest of the code for you. 4) Now, you need to call a method that prints some text to the standard system output. IntelliJ IDEA offers you code completion. If you type Sy you will see a drop-down of likely classes you might want to call. You want System so you can press Control+ dot on the highlighted option. Note: It’s case-sensitive, typing in sy rather than Sy will give you different results! 7) IntelliJ IDEA will also place the caret in the brackets, so you can provide the argument to the method. Type in a quote mark » and IntelliJ IDEA will close the quote mark for you. You can now type your text, Hello World in between the quotes. Note: Instead of the above steps, you can also type sout to see a live template that will create the code construct for you as well, however we wanted to show you code completion! Congratulations, you’ve just created your first Java application! Java files like this one can be compiled into bytecode and run in IntelliJ IDEA. Let’s take a look at that in the next step. Создание и запуск первого Java-приложения (часть 1)Перед началом работыСоздание проектаЕсли ни один проект в данный момент не открыт, нажмите кнопку Create New Project на экране приветствия. В противном случае, выберите пункт New Project в меню File. В результате откроется мастер создания проекта. В левой панели выберите Java Module. В правой части страницы, в поле Project name, введите название проекта: HelloWorld. Если до этого вы никогда не настраивали JDK в IntelliJ IDEA в (в таком случае в поле Project SDK стоит ), необходимо сделать это сейчас. Вместо нажмите New и в подменю выберите JDK. В окне Select Home Directory for JDK выберите директорию, в которую устанавливалось JDK и нажмите ОК. Версия JDK, которую вы выбрали, появится в поле Project SDK. Кликните Next. Учтите, что указанная версия JDK будет связана по умолчанию со всеми проектами и Java модулями, которые в дальнейшем будут создаваться. На следующей странице осуществляется выбор мастера для указания дополнительных технологий, которые будут поддерживаться в нашем модуле. Поскольку наше приложение будет «старым добрым приложением Java», мы не нуждаемся в любой из этих технологий. Так что просто нажмите кнопку Finish. Подождите, пока IntelliJ IDEA создает необходимые структуры проекта. Когда этот процесс завершится, вы можете увидеть структуру Вашего нового проекта в окне Project. Изучение структуры проектаСоздание пакетаВ меню New выберите Package. (можно использовать стрелки вверх и вниз для навигации по меню, ENTER для выбора выделенного элемента) В открывшемся окне New Package введите имя пакета (com.example.helloworld). Нажмите кнопку ОК (или клавишу ENTER). Новый пакет появится окне Project. Создание классаНажмите ALT + INSERT. В окне New из списка доступных действий с выделенным пакетом com.example.helloworld выбираем Java Class и нажимаем Enter. В появившемся окне Create New Class в поле Name вводим имя HelloWorld. В поле Kind оставляем тип Class и нажимаем Enter, чтобы подтвердить создание класса. Созданный класс HelloWorld появляется в структуре проекта: На этом все приготовления закончены. Сам процесс написания нашего первого кода будет разобран во второй части статьи. Источники информации:
|