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 ).
Alternatively, in the Project tool window, right-click the class you need and from the context menu, select Recompile ‘class name’ .
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
When you compile your source code, IntelliJ IDEA automatically creates an output directory that contains compiled .class files.

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 <ProjectFolder>/out part of the output path. If you do so (say, specify some <OutputFolder> instead of <ProjectFolder>/out ) but don’t redefine the paths at the module level, the compilation results will go to <OutputFolder>/production/<ModuleName> and <OutputFolder>/test/<ModuleName> .
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 ).
In Project Settings , select Project and in the Project compiler output field, specify the corresponding path.

For modules, select Modules , the module you need and the Paths tab. Change the location of the output folder under the Compiler output section.
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
Press Ctrl+Alt+S to open the IDE settings and select Build, Execution, Deployment | Compiler .
On the Compiler page, select Build project automatically .
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 | 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
From the main menu, select Run | Edit Configurations .
In the dialog that opens, create a new or open an existing run configuration.
Click the Modify options link.
In the Add Run Options list, under the Before Launch section, select Add before launch task . The list of tasks becomes available and the Build will be selected. Click to disable it.
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
When the code is compiled and ready, you can package your application in a Java archive (JAR) to share it with other developers. A built Java archive is called an artifact .
Create an artifact configuration for the JAR
From the main menu, select File | Project Structure Ctrl+Alt+Shift+S and click Artifacts .
Click , point to JAR , and select From modules with dependencies .
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
From the main menu, select Build | Build Artifacts .
Point to the created .jar ( HelloWorld:jar ) and select Build .
If you now look at the out/artifacts folder, you’ll find your .jar file there.
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
Press Ctrl+Shift+A , find and run the Edit Configurations action.
In the Run/Debug Configurations dialog, click and select JAR Application .
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.
Under Before launch , click , select Build Artifacts in the dialog that opens.
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.
Русские Блоги
Статья 10: Режим компиляции Intellij Idea введение и настройки и выбор компилятора
По сравнению с автоматической компиляцией ECLIPSE в режиме реального времени, компиляция Intellij Idex является более маркуровным, хотя INTELLIJ IDEA также может быть скомпилирована путем настройки, но она слишком расточина, поэтому она не рекомендуется. Compilation Intellij Compilation в дополнение к вручную, нажав на кнопку компиляции, вы можете настроить событие компиляции до прогона «контейнера», сначала компилируйте. По умолчанию Идея Intellij также устанавливается это, поэтому в реальном развитии нам не нужно обращать внимание на компиляцию этого. Хотя идея Intellij не имеет компиляции в реальном времени (не настроен), это не влияет на автоматический код кода. Но для нескольких классов между ассоциациями или ждать Build или же Rebuild Вы будете делать соответствующие проверки при запусках.

- Этикетка 1: строить проект, собирать проект;
- Задача 2: сборка модуля, компиляционный модуль;
- TAG 3: RECOLLIE, перекомпилируйте файл класса;
- Цель 4: Восстановление проекта восстановления проекта.
Как показано на рисунке выше, в Intellij Idey, существует три типа методов компиляции, соответственно:
- Build : Компилируйте выбранную цель (проект или модуль), но только модифицированный файл скомпилируется, а файл, который не был изменен, не будет скомпилирован.
- Recompile : Для выбранной цели (файл класса Java), обязательная компиляция, независимо от того, изменена ли цель.
- Rebuild : Для выбранной цели (проекта), обязательной компиляции, независимо от того, модифицирована ли цель, поскольку цель восстановления является только проектом, поэтому каждое время цветов восстановления относительно длительное.
Далее давайте посмотрим на компиляцию перед запуском:

Как показано выше, идея Intellij выполняется по умолчанию перед запуском проекта. Build работать.
Затем давайте посмотрим на настройки и подборку компилятора IDELEID IDEA:

- Цель 1: установить автоматический элемент компиляции;
- Примечание 2: Компиляция настройки heap размер;
- Тег 3: время установки VM параметр.
Как показано на рисунке выше, мы расположены » Build、Execution、Deployment > Complie «Страница, проверяя Этикетка 1. Показано Build project automatically Мы можем создать идею Intellij для автоматической компиляции; Этикетка 2. Указывает набор компиляции heap Размер, по умолчанию 700, если вы используете 64-битные машины, в случае памяти, вы можете попытаться изменить его до 1500 или более, поэтому, если мы сообщим об этом, когда мы компилируем OutOfMemoryError Ошибка, вы также можете изменить (уменьшить) этот параметр; Этикетка 3 Указывает параметры виртуальной машины для времени компиляции, это может быть персонализировано в соответствии с требованиями, в целом, он может быть по умолчанию.

Как показано на рисунке выше, мы расположены » Build、Execution、Deployment > Compiler > Excludes «Страница, вы можете нажать Этикетка 1. Показано + с участием — Добавьте или удалите каталог (или файл), чтобы скомпилировать исключение. При компиляции проекта, если какая-либо из компилируемых файлов не скомпилирована, идея Intellij не может запустить, и все вопросы должны быть решены и после компиляции, Imele Idea может работать. Тем не менее, можно компилировать файловую компиляцию пакета каталога в процессе разработки, но мы не сможем его изменить. В это время мы можем рассмотреть возможность добавления пакета в список компиляций, например, проект может запустить ЛА!

- Задача 1: используйте компиляцию;
- Примечание 2: версия Bytecode Project;
- Цель 3: версия Bytecode Per-Module.
Как показано на рисунке выше, мы расположены » Build、Execution、Deployment > Compiler > Java Compiler "Страница, Этикетка 1. Компилятор, поддерживаемый Intellij Idex, включая Javac, Eclipse, AJC и т. Д., По умолчанию Javac, также рекомендуется использовать Javac; Этикетка 2. Отображаемая версия проекта скомпилирована, которая обычно выбрана текущей версией Master Master JDK; Этикетка 3 Указывает на то, что он может быть целена Project Под каждой Module Особые потребности отдельно установлены разные bytecode version Конечно, предпосылка заключается в том, что наш компьютер должен заранее установить соответствующую версию JDK.
Compiling and Running
Use IntelliJ IDEA to run your Hello World application.
Now you have written your 'HelloWorld.java' class, you need to compile and run it. IntelliJ IDEA can do this for you. There are lots of ways you can run an application but to start with, you can click the green arrows to the left of the method. These are known as gutter icons.
You'll notice that there are two green arrows. The top one is adjacent to the class, and it will run the class. Our class only contains Java's main method so that is all that it will run. However, if you're working with classes with multiple tests in for example, using this green run arrow will run all the tests in the class.
The second green arrow is adjacent to Java's main method. Clicking this will run Java's main method. For the purpose of our application, both the green arrows do the same thing. When you click on the green arrow you'll get different options including debug, but we will just run it for now so select that option.
IntelliJ IDEA will now compile the file into a class file and then run it. The output of the run is shown in the Run tool window at the bottom of your screen.
The Run Window
Let's take a look at your Run Window in more detail.
The first line shows the command that was used to run the program. We don't usually need to worry about what this was, but it's useful to know in case you want to see exactly what was run and how. For example, if you scroll to the right you will see com.example.helloworld.HelloWorld . This tells you that it was your HelloWorld class that was run. You can also see exactly which JDK was used, which can be useful if you have multiple versions of Java on the same machine.
The second line in this window is the output of your program — the "Hello World" statement that you told it to print.
The last line, which says Process finished with exit code 0 shows the program ran without an error.
What IntelliJ IDEA Created
Let's take a quick look at what happened when you ran the application. IntelliJ IDEA compiled your HelloWorld.java file into a class file. By default, the IDE created a folder called out . Production code, meaning code that isn't test code, is put into the production folder within the out folder. IntelliJ IDEA creates a folder for our HelloWorld project and then the directory structure for our package. The compiled class file HelloWorld.class can be found at the end of this directory hierarchy.
Run Configurations and Shortcuts
IntelliJ IDEA also created a run configuration for the application we ran. If you want to, you can run or debug any run configurations from the navigation bar. We will take a more detailed look at run configurations later in this tutorial.
If you want to go back to the Run Window, you can use Cmd+4 on macOS, or Alt+4 on Windows to open it and the same shortcut again to close it and return the focus back on the editor.
Name already in use
OAP / articles / ide_idea.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Основы работы с IntelliJ IDEA. Интерфейс программы
Для написания Java-программы (и естественно, Kotlin) по большому счету достаточно обыкновенного текстового редактора, но, конечно же, такой вариант просто несопоставим с использованием профессиональных сред разработки приложений, так называемых IDE (Integrated Development Environment).
IntelliJ IDEA – это интегрированная среда разработки программного обеспечения на Java/Kotlin от компании JetBrains. Кстати, не только на них. Среда с успехом используется и для других языков программирования, например, Scala. Первая версия программы появилась в 2001 г. и с тех пор программа неуклонно повышает свой рейтинг популярности. IntelliJ IDEA выпускается в двух редакциях: Community Edition и Ultimate Edition. Первая версия является полностью бесплатной. Вторая версия распространяется под различными лицензиями и, как декларируется, может использоваться бесплатно для разработки проектов с открытым программным кодом.
Версии отличаются также поддерживаемыми технологиями.
- Ultimate Edition:
- полнофункциональная среда разработки под JVM и разработке на различных языках: Java, Kotlin, PHP, JavaScript, HTML, CSS, SQL, Ruby, Python;
- поддержка технологий Java EE, Spring/Hibernate и других;
- внедрение и отладка с большинством серверов приложений.
- Community Edition:
- полнофункциональная среда разработки для Java SE, Kotlin, Groovy и Scala;
- мощная среда для разработки под Google Android.
Программа содержит полный набор необходимых для создания полноценных приложений компонент: редактор, среда компиляции и выполнения, а также отладчик.
Естественно, IntelliJ IDEA – не единственная среда создания приложений для Java, достаточно припомнить популярную Eclipse или NetBeans, так что разработчику есть из чего выбирать.
Скопировать дистрибутив можно с сайта разработчика компании JetBrains по ссылке http://www.jetbrains.com/idea/. Установка IntelliJ IDEA проблем не вызывает. Отмечу только, что при инсталляции установите ассоциацию программы (Create associations) с файлами Java и Kotlin.
После установки при первоначальной загрузке IntelliJ IDEA появляется стартовое окно «Welcome to IntelliJ IDEA», позволяющее загрузить либо открыть проект, импортировать проект, выполнить его загрузку из репозитория нескольких систем контроля версий («Check out from Version Control»). При наличии в проекте файлов настройки сборки для Maven или Gradle, IntelliJ IDEA предложит вам использовать их для конфигурации.
После работы с определенным проектом, он запоминается, и при последующем запуске программы происходит загрузка последнего открытого проекта. Впрочем, это происходит при настройках программы по умолчанию, когда в настройках программы (File — Settings) в группе Appearance & Behavior (Внешний вид и поведение), System Setting (Настройки программы) установлен флажок для поля-метки Reopen last project on startup (Открывать последний проект при загрузке).

Основное окно программы в общем виде состоит из трех областей, называемых также инструментальными окнами (на рисунке отмечены красным) и окна редактора (оранжевое).

Инструментальные окна располагаются по периметру окна редактора, то есть слева, справа и внизу от него на полях главного окна, которые в дальнейшем будем называть боковыми панелями (sidebar в терминологии программы). Поскольку инструментальные окна отображают разноплановую информацию, то каждая боковая панель содержит ряд вкладок, которые открываются при выполнении определенной команды. Переход к нужной вкладке (инструментальному окну) осуществляется щелчком на ее названии, которые располагаются на боковых панелях главного окна. Названию некоторых вкладок инструментальных окон предваряет цифра. Используя клавишу совместно с этой цифрой, можно быстро перейти к этой вкладке, попутно открыв ее, если она находится в свернутом положении, либо, наоборот, свернуть ее.
Перед кратким описанием инструментальных окон оговорюсь, что рассматриваемая структура расположения предлагается такой, какой она является после установки программы по умолчанию. Именно такое расположение я и буду рассматривать далее. Однако это вовсе не означает, что инструментальные окна нельзя расположить в других местах главного окна, о чем речь пойдет ниже.
Окно редактора отображается постоянно, занимая большую часть основного окна. Оно может содержать несколько вкладок, отображающих содержимое разных файлов проекта. О содержимом вкладки сигнализирует как расширение файла в названии вкладки, так и пиктограмма перед названием.
Программа содержит внушительный инструментарий управления вкладками окна. Так, расположение вкладок можно произвольно изменять, располагая их, например, горизонтально, перебрасывая файлы из одной группы вкладок в другую, что достигается при помощи группы команд Windows — Editor Tabs либо из контекстного меню, вызываемого на вкладке окна редактирования. При необходимости конкретную вкладку можно закрепить, что бывает полезным при большом количестве вкладок, когда все они не помещаются в окне редактирования, для чего используем команду Pin Tab, о чем речь пойдет ниже.
С правого края окна (в районе полосы прокрутки) могут находятся горизонтальные линии, отмечающие проблемные блоки кода, содержащие ошибки и предупреждения. А в правом вершнем углу отображается общее сосотяние файла (красный — есть ошибки, желтый — есть предупреждения, зеленый — все нормально). Подробнее об этом также позже.
По левому краю окна редактирования расположены метки блоков кода, при помощи которых можно быстро свернуть блок за ненадобностью либо вновь его развернуть. С этой же стороны окна располагаются точки останова (при их наличии), советы по модификации кода и некоторая другая информация.

Для отображения нумерации строк программного кода следует вызвать контекстное меню (кликнуть правой кнопкой мыши) на вертикальной полосе в левой части окна редактирования и выбрать Show Lines Numbers (Отображать нумерацию строк). Однако при таком действии отображение строк осуществляется только в текущем сеансе. Для постоянного же отображения нумерации строк программного кода следует в настройках раскрыть последовательно пункты Editor (Редактор), General (Общие настройки), Appearance (Внешний вид) и установить флажок для поля-метки Show line numbers (Отображать номера строк).
Сам программный код (подсветка текста, шрифты) оформляются в соответствии с настройками программы, о чем речь пойдет позже.
Инструментальное окно проекта
На левой боковой панели отображается инструментальное окно проекта. Оно содержит вкладку иерархической структуры проекта (Project), вкладку структуры (списка метода) класса (Structure) и вкладку Favorites (Избранное), в которой отображаются закладки и точки останова.
Выбор во вкладке структуры проекта приводит к отображению его содержимого в окне редактора. Поскольку код практически любого класса содержит множество методов/функций, то вкладка «Structure» как раз и отображает их список. Он может быть упорядочен как по алфавиту (Sort by Alphabetically), так и в порядке их расположения в (Sort by Visibility). Щелчок на имени класса инициирует переход на начало метода или функции в окне редактора.

Инструментальное окно Избранное
В нижней части левой боковой панели основного окна можно вывести инструментальное окно «Favorites» (Избранное), содержащее, например, список точек останова и закладок, обеспечивая тем самым к ним быстрый доступ.
Инструментальное окно с инструментами сборки проектов
Данное окно располагается на правой боковой панели. Оно изначально содержит вкладки для наиболее распространенных инструментов сборки проектов Java – Gradle (или Maven) и Ant.
Инструментальное окно вывода
Окно располагается на нижней инструментальной панели. В нем в зависимости от характера информации отображаются, например, сообщения компиляции («Messages»), консольный ввод/вывод («Terminal»), контроль изменений проекта («Version Control»), результаты работы отладчика («Debug») и некоторые другие.
Создается проект просто: File — New — Project. А вот дальше возникают вопросы: какого типа у нас проект, какие библиотеки нужны.

Мы в своих проектах будем использовать Gradle и Kotlin/JVM. Если со вторым пунктом (язык программирования и реализация под JavaVirualMachine) сомнений нет, то с первым пока непонятно. Я выбрал Gradle, потому что он используется по-умолчанию в Android Studio с которым мы познакомимся в следующем году. Но что вообще означают эти слова: Maven, Gradle?
Если коротко, то это системы сборки проектов, а если подробно, то читайте, например, тут
При создания нового проекта система создает для нас необходимую структуру каталогов и файлы настроек. Нам из всего этого пока понадобится только каталог с исходными кодами и настройки системы сборки проектов:

Для создания нового файла нужно кликнуть правой кнопкой мыши на подкаталоге kotlin в каталоге src и выбрать Kotlin File/Class
В появившемся окне введите название файла и выберите из списка File

В первом созданном файле (у нас он называется main.kt, но это не обязательно) сделайте точку входа в программу:
Любая программа (консольная, про андроид мы пока не говорим) начинается с функции main.
В лабораторных работах, чтобы не плодить проекты, мы будем использовать один и тот же проект с одним главным файлом, а для разных задач создавать дополнительные файлы, например:
Все файлы одного пакета (название пакета мы не задавали, но он назначается системой) собираются в одину программу. Таким образом весь код лабораторной работы мы будем писать в отдельном файле (lab1.kt), а вызывать его из функции main. Это упростит нам работу с репозиторием (с ним мы познакомимся на следующем занатии) и уменьшит количество мусора на диске.