Как запустить код в intellij idea java
Перейти к содержимому

Как запустить код в intellij idea java

  • автор:

Run a Java application

This tutorial explains how to quickly run a Java application. It also covers the setup required to run a Java application, such as creating a new project, configuring the JDK, and setting up run configurations with various options.

Create a new project

Launch IntelliJ IDEA.

If the Welcome screen opens, click New Project . Otherwise, from the main menu, select File | New | Project .

From the list on the left, select New Project . Name the new project.

Select the following project options:

Build system : Maven

Add sample code : enabled

From the JDK list, select the latest available Oracle OpenJDK version.

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.

If you don’t have the necessary JDK on your computer, select Download JDK .

Run the application

When the project is created, in the Project tool window ( Alt+1 ), locate the src | main | java | Main.java file and open it in the editor.

Replace the existing code with the following code sample:

In the editor, click the gutter icon to run the application.

IntelliJ IDEA runs your code. After that, the Run tool window opens at the bottom of the screen.

The application has run successfully, that is why you will see the Process finished with exit code 0 message in the output.

Application has compiled

When you clicked Run , IntelliJ IDEA created a temporary run configuration named after the Main class. The number of temporary configurations is limited to 5 by default, so the older ones are automatically deleted when new ones are added. That is why it is makes sense to save the temporary configurations that you want to keep.

You change the maximum number of temporary configurations in Settings | Advanced Settings | IDE | Temporary configurations limit .

Save the run configuration

From the main menu, select Run | Edit Configurations .

In the area on the left, select the Main configuration, and then click the icon on the toolbar above.

The icons of temporary configurations are semi-transparent. So, as soon as the configuration is saved, its icon will become brighter.

Click Apply . Do not close the dialog yet.

For the full list of option in this run/debug configuration, refer to Run/debug configuration: Application.

Enable the Store as project file option to place the run configuration under version control and share it with other project users.

Save console output to a file

Now let’s copy this configuration and modify it so that the IDE saves the console output to a file every time you run the configuration. This might be useful if you use console output for logging.

In the area on the left, click the Main configuration and then click on the toolbar.

This will create a copy of the run configuration.

In the area on the right, rename the configuration to SaveConsoleOutput .

Click Modify options and from the Logs settings group, select Save console output to file .

Specify the path to the file to which the IDE will write the output. If the file does not exist, it will be created automatically.

In our case, we will create a file in the project directory, so the path that we specify is /Users/jetbrains/IdeaProjects/RunApplication/console.txt .

Apply the changes and close the dialog.

Run the saved configuration

Make sure that SaveConsoleOutput is selected in the Run widget in the window header and click next to it or press Shift+F10 .

When the IDE finishes running the configuration, locate the new file with the console output in the Project tool window and make sure it has content.

If you store logs in the project directory, add the logs folder to .gitignore to avoid sharing it through VCS. You can also mark the folder as excluded to exclude it from indexing and search.

Run configurations allow you to run the same application with different parameters. Now that you have two configurations, you can choose between them according to your needs. For example, if you do not need to save the console output every single time you run the application, you can run the Main configuration that does not have this setting.

Use the Run widget in the window header to switch between configurations:

Run widget switcher

Let’s take a look at another scenario.

Change the code

Imagine that our code sample has a problem.

In the Main.java file, remove:

Instead, paste the following code:

In the editor, click the gutter icon to run the application.

The application hangs for several seconds and then fails with OutOfMemoryError . Our program declares an infinite stream of integers and then tries to convert it into a list using the toList() method. Since the stream is infinite, the toList() method will never return, and the program will keep running indefinitely, consuming system resources.

Application failed with OutOfMemoryError

In this case, we can add a VM option that will create an .hprof file for us if our application fails with OutOfMemoryError . Later on, we will be able to analyze this file in detail using the built-in profiler.

This is useful if you do not know the reason for OutOfMemoryError and would like to investigate it further.

Add the VM options

From the main menu, select Run | Edit Configurations .

In the area on the left, click the Main configuration and then click on the toolbar to duplicate the configuration.

Rename the configuration to OutOfMemory .

Open the Modify options list and click Add VM options .

The VM Options field appears in the dialog. In this filed, add the following option:

Apply the changes and close the dialog.

Make sure that the OutOfMemory configuration is selected in the Run widget and click next to it or press Shift+F10 .

The Run tool window opens showing you that the OutOfMemoryError exception has been thrown. Since we have configured the corresponding VM option, the IDE has created an .hprof file in your project directory.

Создание и запуск первого Java-приложения (часть 1)

Создание и запуск первого Java-приложения (часть 1) - 1

Чтобы получить представление о том, как IntelliJ IDEA поможет вам в разработке и запуске Java-приложений, мы предлагаем вам создать и запустить простейший пример «Hello, World» в данной программе. Таким образом, вы сможете узнать об основных IDE функциях без необходимости вдаваться в детали кода. Пошаговая инструкция поможет вам не запутаться в тонкостях запуска и настройки программы.

Перед началом работы

Создание проекта

Если ни один проект в данный момент не открыт, нажмите кнопку Create New Project на экране приветствия. В противном случае, выберите пункт New Project в меню File. В результате откроется мастер создания проекта.

В левой панели выберите Java Module.

В правой части страницы, в поле Project name, введите название проекта: HelloWorld.

Если до этого вы никогда не настраивали JDK в IntelliJ IDEA в (в таком случае в поле Project SDK стоит <Nоne>), необходимо сделать это сейчас.

Вместо <Nоne> нажмите New и в подменю выберите JDK.

В окне Select Home Directory for JDK выберите директорию, в которую устанавливалось JDK и нажмите ОК.

Создание и запуск первого Java-приложения (часть 1) - 3

Версия JDK, которую вы выбрали, появится в поле Project SDK.

Создание и запуск первого Java-приложения (часть 1) - 4

Кликните Next.

Учтите, что указанная версия JDK будет связана по умолчанию со всеми проектами и Java модулями, которые в дальнейшем будут создаваться.

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

Создание и запуск первого Java-приложения (часть 1) - 5

Поскольку наше приложение будет «старым добрым приложением Java», мы не нуждаемся в любой из этих технологий. Так что просто нажмите кнопку Finish.

Подождите, пока IntelliJ IDEA создает необходимые структуры проекта. Когда этот процесс завершится, вы можете увидеть структуру Вашего нового проекта в окне Project.

Изучение структуры проекта

HelloWorld. Это узел, содержащий ваш Java модуль. Папки .idea и файлы внутри директории HelloWorld.iml используются для хранения данных конфигурации вашего проекта и модулей соответственно.SRC папки содержат исходный код.

Создание пакета

В окне инструментов Project выберите папку SRC и нажмите ALT + INSERT. (В качестве альтернативы, вы можете выбрать File -> New, или New из контекстного меню для папки SRC).

В меню New выберите Package. (можно использовать стрелки вверх и вниз для навигации по меню, ENTER для выбора выделенного элемента)

В открывшемся окне New Package введите имя пакета (com.example.helloworld). Нажмите кнопку ОК (или клавишу ENTER).

Создание и запуск первого Java-приложения (часть 1) - 8

Новый пакет появится окне Project.

Создание класса

Нажмите ALT + INSERT. В окне New из списка доступных действий с выделенным пакетом com.example.helloworld выбираем Java Class и нажимаем Enter.

В появившемся окне Create New Class в поле Name вводим имя HelloWorld. В поле Kind оставляем тип Class и нажимаем Enter, чтобы подтвердить создание класса.

Создание и запуск первого Java-приложения (часть 1) - 11

Созданный класс HelloWorld появляется в структуре проекта:

Создание и запуск первого Java-приложения (часть 1) - 12

На этом все приготовления закончены. Сам процесс написания нашего первого кода будет разобран во второй части статьи.

Знакомство с IntelliJ IDEA: установка, создание Java-проекта и первая Java-программа

IntelliJ IDEA — одна из самых популярных интегрированных сред разработки (IDE) для языка Java. Благодаря мощному инструментарию и удобному интерфейсу, IntelliJ IDEA позволяет быстро и эффективно создавать, и отлаживать Java-приложения разной сложности.

В этой статье мы рассмотрим процесс установки IntelliJ IDEA на такие операционные системы, как: Windows, Linux и macOS. Также создадим Java-проект и выполним первую Java-программу.

Загрузка и установка IntelliJ IDEA

Скачать IntelliJ IDEA для Windows, Linux и macOS можно с официальной страницы JetBrains (компания-разработчик IntelliJ IDEA).

Существуют две вариации IntelliJ IDEA: Community Edition и Ultimate. Ultimate является более профессиональным решением с дополнительными возможностями, отсутствующими в Community Edition. Однако Ultimate-версия доступна только по платной подписке, в то время как Community Edition полностью бесплатна. Более подробно про различия между этими двумя редакциями можно прочитать здесь.

Далее показаны шаги для загрузки и установки IntelliJ IDEA Community Edition на Windows, Linux и macOS.

Установка IntelliJ IDEA в Windows

Шаг №2: Выберите раздел Windows.

Шаг №3: Под редакцией Community Edition выберите желаемый способ установки — с помощью установщика (.exe) или архива (.zip). Установщик для архитектуры х86-64 — .exe, для 64-битной архитектуры ARM — .exe (ARM64). Дальнейшие шаги основаны на использовании установщика.

Шаг №4: Запустите установщик и нажмите Next:

Шаг №5: Выберите/подтвердите конечный путь установки IntelliJ IDEA:

Шаг №6: Рекомендуется установить флажок возле пункта Add «bin» folder to the PATH, чтобы система могла находить и запускать исполняемые файлы IntelliJ IDEA без необходимости указывать полный путь к ним. Чтобы создать ярлык IntelliJ IDEA на рабочем столе, установите флажок возле пункта IntelliJ IDEA Community Edition. Также рекомендуется выбрать пункт Add «Open Folder as Project», чтобы открывать папки в IntelliJ IDEA и работать с ними как с проектами. Создание ассоциации с .java-файлами позволит IntelliJ IDEA стать стандартным инструментом для открытия .java-файлов.

Шаг №7: Определите название папки, в которой будет размещен ярлык IntelliJ IDEA. По умолчанию IntelliJ IDEA предлагает создать папку JetBrains и разместить ярлык программы внутри нее.

Шаг №8: Если вы ставили флажок напротив пункта Add «bin» folder to the PATH, для завершения установки вам необходимо перезагрузить компьютер. Если вы хотите выполнить перезагрузку сейчас, выберите Reboot now. Если же вы планируете выполнить перезагрузку позже, выберите I want to manually reboot later.

Установка IntelliJ IDEA в Linux

Шаг №2: Выберите раздел Linux.

Шаг №3: Для архитектуры х86-64 под редакцией Community Edition выберите .tar.gz, для ARM64 — .tar.gz (ARM64). Затем нажмите на кнопку Download.

Шаг №4: Распакуйте архив в нужную директорию, например, /opt/ . Для этого введите команду типа:

sudo tar -xzf путь-к-скачанному-архиву -C /opt/

Замените путь-к-скачанному-архиву на фактический путь к скачанному архиву. Если вы хотите распаковать архив в другую директорию, замените /opt/ соответствующим путем. Например:

Шаг №5: Рекомендуется изменить владельца для IntelliJ IDEA с помощью следующей команды:

sudo chown -R $USER:$USER путь-к-распакованному-архиву

Замените путь-к-распакованному-архиву на фактический путь к распакованному архиву. Эта команда изменит права доступа для текущего пользователя. Если вы хотите изменить права доступа для другого пользователя системы, замените $USER на имя (username) этого пользователя.

Шаг №6: Выполните следующую команду, чтобы запустить IntelliJ IDEA:

Не забудьте заменить путь-к-распакованному-архиву , например, /opt/idea-IC-231.9011.34/bin/idea.sh

Шаг №7: Нажмите на значок шестеренки внизу слева в открывшейся программе и выберите пункт Create Desktop Entry, чтобы добавить ярлык IntelliJ IDEA в меню приложений:


Установка IntelliJ IDEA в macOS

Шаг №2: Выберите раздел macOS.

Шаг №3: Для архитектуры х86-64 под редакцией Community Edition выберите .dmg (Intel), для Apple Silicon — .dmg (Apple Silicon). Затем нажмите на кнопку Download.

Шаг №4: Запустите скачанный файл и перетащите иконку IntelliJ IDEA в каталог Applications.

Создание Java-проекта

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

Для создания Java-проекта нужно открыть IntelliJ IDEA и нажать на кнопку New Project:

После этого должно открыться окно настройки проекта:

В поле Name введите название проекта (оно может быть любым).

В поле Location нужно указать расположение проекта. Если вы не знаете, что такое Git, снимите флажок возле пункта Create Git repository.

В пункте Language выберите Java.

В пункте Build system выберите IntelliJ.

В пункте JDK убедитесь, что версия JDK была правильно определена. Если у вас отсутствует JDK, вы можете загрузить его, следуя инструкциям из этого урока.

Снимите флажок возле пункта Add sample code.

Нажмите на кнопку Create.

Первая Java-программа в IntelliJ IDEA

После создания проекта, если вы сняли флажок с пункта Add sample code, должна создаться структура проекта без файлов исходного кода. В Java программы пишутся в файлах с расширением .java. Единицами структуры любой Java-программы или целого Java-приложения являются Java-классы, которые размещаются в .java-файлах. Обычно каждый Java-класс находится в отдельном .java-файле, причем название Java-класса должно совпадать с названием .java-файла.

Для создания Java-класса нажмите ПКМ по папке src в окне инструментов проекта (англ. «Project tool window»; область интерфейса, где отображаются все файлы и структура каталогов проекта). Затем наведите курсор на пункт New и выберите Java Class.

В появившемся окне введите название Java-класса и нажмите Enter. Например:

После этого должен автоматически создаться .java-файл, название которого соответствует введенному названию Java-класса. Внутри этого .java-файла будет создан пустой класс с таким же именем:

Обратите внимание, что на данном этапе программу нельзя запустить, так как отсутствует точка входа в программу — главный метод main():

Intro

Daniel Padua Ferreira

To those who develop in java nowadays, it’s almost impossible to miss Spring framework and more specifically Spring Boot. Using this development stack, we gain more productivity and agility from small to large sized java projects. In this guide I’ll demonstrate how to install, configure IntelliJ IDEA and create a simple Hello-World using java, IntelliJ IDEA and spring boot.

The github repository of the example project of this post, can be found at: https://github.com/danielpadua/java-spring-idea-example

Requirements

  • Java JDK 8 or higher

Installing IntelliJ IDEA

Use the following sections based in which operational system you’ll be using:

Windows

In Windows we have 2 options:

  • Direct download

Go to jetbrains download page, select the latest version (on the writing date of this guide is the 2019.1.1) and install it using NNF (next, next, next and finish).

  • Using a package manager (Chocolatey)

Open powershell and install IntelliJ IDEA using the following command line:

Linux

In Linux we also have 2 options:

  • Direct download

Go to jetbrains download page, select the latest version (on the writing date of this guide is the 2019.1.1), extract the .tar.gz file and execute the /bin/idea.sh file.

  • Using a package manager

Depending in which Linux distro you are using, you’ll use a different package manager. For instance, debian based distros, like the popular ubuntu, use apt-get. For Red Hat (or RHEL) based distros use yum or dnf. Search the best way to install IntelliJ IDEA using your package manager.

macOS

In macOS we have 2 options again:

  • Direct download

Go to jetbrains download page, select the latest version (on the writing date of this guide is the 2019.1.1) and install it as usual, dragging the app from the .dmg file to the apps folder of your mac.

  • Using a package manager (Homebrew)

Open your favorite terminal and install IntelliJ IDEA using the following command line:

Configuring IntelliJ IDEA

With IntelliJ IDEA installed, the configuration is pretty simple. When you execute IDEA you will be questioned about some configurations like: theme color, shortcut key mapping and plugins. Let’s leave default config and begin.

Creating the project

As soon as it starts, you’ll see the following screen:

Unfortunately using IntelliJ IDEA Community, according to the documentation, there’s no support to create Spring Boot projects using Spring Initializr through the IDE in Community version, only in the Ultimate Edition. So, we have two choices that we can explore:

Use Spring Initializr Web

Access: https://start.spring.io, and fill the fields like below:

Don’t forget to select Web as dependency. Click Generate Project to download the project zip file. Extract it to a directory of your choice, go back to IntelliJ IDEA and select Import Project. Navigate to project’s directory and select the pom.xml file. You’ll see a window that is responsible for importing the Maven project, leave the defaults configs:

Select the project to import and click next:

In the next screen, set the JDK version that you installed:

In the next screen confirm the project name and click finish.

Creating a Maven project and add Spring manually

In IntelliJ IDEA’s initial screen, select Create New Project, located on the left side tab and select Maven, on the right side, select the JDK version and click next:

When selecting the archetype, IntelliJ IDEA will assume that you will use Quickstart archetype, which is ok for our goal.

In the next screen specify the GroupId, ArtifactId and the Version and click next:

After you just have to name your project and click finish:

With the project created, configure pom.xml according to the following snippet:

After you update pom.xml a notification will pop-up at the inferior right side of the screen:

Click Import Changes for Maven refresh all project dependencies.

Now we’ll create a class that will contain the main function of the project. Remember that creating a class in default package is not a good java practice, so, click in source folder main/java and create a package:

Write the name of the package, in my example was: br.com.danielpadua.java_spring_idea_example, and create a class inside this package named ExampleApplication.java, and write the code:

Don’t forget the unit tests main class too, repeat package creation step and create a class named: ExampleApplicationTests.java and write the code:

At this moment we’ll have basically the same project structure that is generated by Spring Initializr at the section above.

Completing the project

With the basic project skeleton created, we just have to create a package to nest the controller that will contain Hello World endpoint. Right click the root package:

Write: controllers and confirm. Inside the generated package, create a class named: ExampleController.java and write the code:

Run the project by right clicking over the main class Application.java and select the option Run ‘Application.main()’:

After clicking run, you should see the output in the Run tab located at screen’s bottom:

To test the app, you only have to open your favorite browser and access: http://localhost:8080/api/example/hello-world, and you should see the Hello World message:

Conclusion

IntelliJ IDEA is the most used IDE for java nowadays and it’s probably the most complete in the opinion of many developers. Community version is a great alternative to traditional eclipse.

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

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