Как сделать папку модулем intellij idea

Modules

In IntelliJ IDEA, a module is an essential part of any project – it’s created automatically together with a project. Projects can contain multiple modules – you can add new modules, group them, and unload the modules you don’t need at the moment.

Generally, modules consist of one or several content roots and a module file, however, modules can exists without content roots. A content root is a folder where you store your code. Usually, it contains subfolders for source code, unit tests, resource files, and so on. A module file (the .iml file) is used for keeping module configuration.

Modules allow you to combine several technologies and frameworks in one application. In IntelliJ IDEA, you can create several modules for a project and each of them can be responsible for its own framework. For more information, refer to Add frameworks (facets).

Module composition shown on a scheme

For more information on how modules are used in projects, refer to Configure projects.

IntelliJ IDEA modules vs Java modules

In version 9, Java introduced the Java Platform Module System. IntelliJ IDEA had already had a concept of modules: every IntelliJ IDEA module built its own classpath. With the introduction of the new Java platform module system, there appeared two systems of modularity: the IntelliJ IDEA modules, and the new Java 9 modules that are configured using module-info.java . This documentation section describes IntelliJ IDEA modules.

For more information on Java 9 support in IntelliJ IDEA refer to the Support for Java 9 Modules in IntelliJ IDEA 2017.1 and Java 9 and IntelliJ IDEA blog posts.

Projects with multiple modules

IntelliJ IDEA allows you to have many modules in one project, and they shouldn’t be just Java. You can have one module for a Java application and another module for a Ruby on Rails application or for any other supported technology.

An application that consists of a client side and a server side is a good example a two-module project.

Add a new module to your project

Select the top-level directory in the Project tool window and press Alt+Insert or select New | Module from the context menu.

The New Module wizard opens.

From the list on the left, select a module type. Name the new module.

From the Language list, select the language that you want to use in your application.

If you want to use a language that is not available in IntelliJ IDEA out of the box (for example, Python or PHP), click the button and select the necessary option.

The IDE will open a dialog in which you can select and install the necessary language plugin. After that, you can close the dialog and keep configuring the new module.

Select the build system that you want to use in your project: the native IntelliJ builder, Maven, or Gradle.

For Gradle, you will also need to select a language for the build script: Groovy or Kotlin.

Select a JDK that you want to use from the JDK list. You can use the project SDK or specify a new one.

Import an existing module

You can import a module to your project by adding the .iml file from another project:

From the main menu, select File | New | Module from Existing Sources .

In the dialog that opens, specify the path the .iml file of the module that you want to import, and click Open .

By doing so, you are attaching another module to the project without physically moving any files. If you don’t need the modules to be located in one folder, the module import is finished, and you can start working with the project normally.

If you want the modules in the same folder, in the Project tool window, drag the imported module to the top-level directory. In this case, the contents of the imported module will be physically transferred to your project’s folder.

For information on how to attach a Maven or Gradle project to your current project, refer to Link a Gradle project to an IntelliJ IDEA project and Link and unlink a Maven project.

Import a module from existing sources

Use these steps to import a project as a module if the project comes from an external model or if you want to create a module from the existing source code that is not necessarily an exported project.

From the main menu, select File | New | Module from Existing Sources .

Select the directory in which your sources, libraries, and other assets are located and click Open .

In the dialog that opens, select Create module from existing sources if you want to create a new module from the existing source code.

Otherwise, select Import project from external model , select the external model that the project uses, and follow the steps of the wizard.

Group modules

In IntelliJ IDEA, you can logically group modules. If you have a large project with multiple modules, grouping will make it easier to navigate through your project. Module groups can be nested: a group can contain other subgroups.

Create a new module group (deprecated)

In earlier versions (2017.2 and earlier), IntelliJ IDEA used explicit groups for joining modules together. If you’ve configured manual module groups, you will be able to continue working with them in later versions of the IDE. Alternatively, you can convert module groups and use qualified names instead.

In the Project tool window ( Alt+1 ), select the modules that you want to group.

You can also do so on the Modules page of the Project Structure dialog ( Ctrl+Alt+Shift+S ).

From the context menu, select Move Module to Group | New Top Level Group .

Name the new group and click OK .

The new group is now created and is marked with the icon.

Select Outside Any Group to exclude the selected module from the group, To This Group to add the module to the group, or To New Subgroup to create a new group in another group.

Convert module groups to qualified names (deprecated)

From the main menu, select File | Convert Module Groups to Qualified Names .

In the next dialog, review the new module names and adjust them if necessary.

Apply the changes and close the dialog.

Group modules by fully qualified names

IntelliJ IDEA 2017.3 and later uses fully qualified names to group modules. For example, if you want to group all CDI modules, add the cdi prefix to their names.

Open the Project Structure dialog Ctrl+Alt+Shift+S and click Modules .

Select the modules you want to group, open the context menu, and click Change Module Names .

Specify a prefix and apply the changes.

To view all modules on the same level in the Project Structure dialog, use the Flatten Modules context menu option.

Module groups won’t be visible in the Project tool window ( Alt+1 ) if the Flatten Modules option is enabled there. You can disable it via the button in the tool window header.

Add items to your project

Once you have created a project, you can start adding new items: create directories and packages, add new classes, import resources, and extend your project by adding more modules.

Create new items

Create a new directory

In the Project tool window ( Alt+1 ), right-click the node in which you want to create a new directory and select New | Directory .

Alternatively, select the node, press Alt+Insert , and click Directory .

Name the new directory and press Enter .

If you want to create several nested directories, specify their names separated with slashes, for example: folder/new-folder .

Create a new package

Packages in Java are used for grouping classes that belong to the same category or provide similar functionality, for structuring and organizing large applications with hundreds of classes.

In the Project tool window ( Alt+1 ), right-click the node within the Sources Root the Sources root iconor Test Sources Root the Test Sources rootin which you want to create a new package, and click New | Package .

Alternatively, select the node, press Alt+Insert , and click Package .

Name the new package and press Enter .

Write package names in lowercase letters. There are some other naming conventions for packages in Java that you should follow.

Create a new empty file

In the Project tool window ( Alt+1 ), right-click the node in which you want to create a new file and click New | File .

Alternatively, select the node, press Alt+Insert , and click File .

Name the new file and specify its extension, for example: File.js , and press Enter .

If the extension you have specified is not associated with any of the file types recognized by IntelliJ IDEA, the Register New File Type Association dialog is displayed. In this dialog, you can associate the extension with one of the recognized file types.

Create a new Java class

In the Project tool window ( Alt+1 ), right-click the node in which you want to create a new class and select New | Java Class .

Alternatively, select the node, press Alt+Insert , and select Java Class .

Name the new class and press Enter .

Follow the Java naming convention as you create new classes.

Together with the file, IntelliJ IDEA automatically generates 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.

You can create a class together with a package. To do so, press Alt+Insert in the Project tool window, select Java Class , and specify the fully qualified name of the class, for example: com.example.helloworld.HelloWorld . For more information, refer to Create a package and a class.

Create a new module

Modules allow you to combine several technologies and frameworks in one application. In IntelliJ IDEA, you can create several modules in one project and each of them can be responsible for its own framework.

Select the top-level directory in the Project tool window and press Alt+Insert or select New | Module from the context menu.

The New Module wizard opens.

From the list on the left, select a module type. Name the new module.

From the Language list, select the language that you want to use in your application.

If you want to use a language that is not available in IntelliJ IDEA out of the box (for example, Python or PHP), click the button and select the necessary option.

The IDE will open a dialog in which you can select and install the necessary language plugin. After that, you can close the dialog and keep configuring the new module.

Select the build system that you want to use in your project: the native IntelliJ builder, Maven, or Gradle.

For Gradle, you will also need to select a language for the build script: Groovy or Kotlin.

Select a JDK that you want to use from the JDK list. You can use the project SDK or specify a new one.

For more information on modules in IntelliJ IDEA, refer to Modules.

Import items

Import files

You can import files to your project using any of the following ways:

Drag the file from your system file manager to the necessary node in the Project tool window ( Alt+1 ).

Copy the file in the system file manager by pressing Ctrl+C and then paste in to the necessary node in the IDE Project tool window by pressing Ctrl+V .

Manually move the file to the project folder in your system file manager.

Import folders

To import a folder to your current project, drag the folder from your system file manager to the Project tool window ( Alt+1 ).

Example: Import an image

Images belong to resource files. They should be stored in a dedicated folder – Resources Root. If you don’t have this folder in your project, create a new directory, right-click it in the Project tool window, and select Mark Directory as | Resources Root .

Copy the file in the file manager and then paste in to the folder with resource files in the IDE Project tool window.

In the dialog that opens, edit the filename and the target location if necessary. Click OK .

Right-click the pasted image in the Project tool window and select Copy | Path From Source Root .

In the class in which you want to use the image, place the caret at the necessary line and press Ctrl+V to paste the path to the image.

Run the class to make sure that the image is inserted correctly.

Import an existing module

You can import a module to your project by adding the .iml file from another project:

From the main menu, select File | New | Module from Existing Sources .

In the dialog that opens, specify the path the .iml file of the module that you want to import, and click Open .

By doing so, you are attaching another module to the project without physically moving any files. If you don’t need the modules to be located in one folder, the module import is finished, and you can start working with the project normally.

If you want the modules in the same folder, in the Project tool window, drag the imported module to the top-level directory. In this case, the contents of the imported module will be physically transferred to your project’s folder.

Как в IntelliJ IDEA в проекте в директории src создать поддиректории?

Начинаю осваивать Java c IDE от JetBrains по видеоурокам.

В этом видео https://youtu.be/xvUFqDKIKJE?t=685 представлена структура папок в проекте src > main > java > Start.java

60a8c691d6e71926149176.jpeg

Я в IDEA создал Java проект и в нем была директория src «синяя». Я решил повторить структуру директорий как в видео и создать поддиректории в src, нажал ПКМ > New, но в выпадающем меню не было пункта для создания поддиректории.

60a8c74d32920078424954.png

Почему так и как это исправить?

  • Вопрос задан более года назад
  • 2968 просмотров

Простой 1 комментарий

  • Facebook
  • Вконтакте
  • Twitter
  • Facebook
  • Вконтакте
  • Twitter

azerphoenix

Прочитайте мой ответ, я ответил вам как создать пакет в Java.

Видимо, для создания вложенного пакета вместо выбора вновь созданного пакета вы кликаете на src.

  • Facebook
  • Вконтакте
  • Twitter

azerphoenix

Добрый день.
Прежде всего желаю вам успехов в изучении Java.

В Java мы оперируем не директориями, а пакетами (Package), хоть по сути пакеты и являются директориями.

Intellij Idea – Deep Dive

Первые четыре главы этого руководства были разработаны, чтобы дать начинающим обзор базового уровня IntelliJ. Этот раздел углубляется в IntelliJ и обсуждает больше о проектах, их формате и других вещах.

Понимание проектов

Проект – это приложение или программное обеспечение, над которым вы работаете. Он может содержать несколько модулей, классов, библиотек, конфигурации и так далее. Это самый верхний элемент в иерархии.

Понимание модулей

Модули имеют одну ступеньку ниже «Проект». Модуль – это отдельная сущность, которую можно компилировать, отлаживать и запускать независимо от других модулей. Один проект может содержать несколько модулей. Вы можете добавлять или удалять модули из проекта в любое время.

В дополнение к этому, мы также можем импортировать существующие модули. Выполните следующие шаги, чтобы импортировать существующие модули –

  • Перейдите в Файл → Структура проекта.
  • Выберите модули и нажмите на значок плюс.
  • Покажет возможность импортировать модуль.

Особенность модулей

Понимание папок

Корень содержимого – это папка, содержащая все файлы, которые составляют ваш модуль. Модуль может иметь более одной папки содержимого. Папки подразделяются на следующие типы –

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

Тесты – назначая эту категорию папке, мы указываем IntelliJ, что это место для модульных тестов. Эта папка может получить доступ к классам из папки Sources.

Ресурсы – представляет различные файлы ресурсов, используемые в проекте, например, изображения, XML и файлы свойств. В процессе компиляции содержимое этой папки копируется как есть в выходную папку.

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

Тестовые ресурсы – это похоже на ресурсы и используется для модульных тестов.

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

Тесты – назначая эту категорию папке, мы указываем IntelliJ, что это место для модульных тестов. Эта папка может получить доступ к классам из папки Sources.

Ресурсы – представляет различные файлы ресурсов, используемые в проекте, например, изображения, XML и файлы свойств. В процессе компиляции содержимое этой папки копируется как есть в выходную папку.

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

Тестовые ресурсы – это похоже на ресурсы и используется для модульных тестов.

Корень контента

Понимание библиотек

Библиотека представляет собой сборник разных классов. Библиотека позволяет многократно использовать код. В Java библиотека может быть заключена в ZIP, Jar или просто папку. Мы можем определить библиотеки на трех разных уровнях. Уровни – глобальный, проектный и модульный.

Глобальный уровень – общий для всех проектов.

Уровень проекта – общий для всех модулей проекта.

Уровень модуля – общий для классов этих модулей.

Глобальный уровень – общий для всех проектов.

Уровень проекта – общий для всех модулей проекта.

Уровень модуля – общий для классов этих модулей.

Понимание граней

Грани являются расширениями модулей. Они добавляют поддержку фреймворкам и технологиям. Когда фасет добавляется в модуль, IntelliJ определяет, что он добавляет поддержку. Например, подсказки и помощь в редакторе, новые инструменты в панели окон, загрузка зависимостей и так далее. Вы можете добавить фасеты из окна Файл → Структура проекта, как показано ниже –

Оконная панель

Артефакты

Артефакты являются результатом проекта. Это может быть простой файл JAR, приложение Java EE или приложение Java EJB. Если мы используем внешние инструменты сборки, такие как Gradle или Maven, IntelliJ автоматически добавит для них артефакт. Артефакты можно создать, перейдя в Файл → Структура проекта, как показано ниже –

Артефакты

Импорт существующего проекта

В этом разделе мы поймем, как импортировать существующий проект. Мы можем импортировать проект двумя способами –

  • Импортируйте его из существующего источника
  • Импортируйте его из модели сборки.

В настоящее время он поддерживает инструменты сборки Gradle и Maven. Импортировать проект –

  • Перейдите в Файл → Создать → Проект из существующего источника.
  • Выберите каталог существующего проекта, Maven’s pom.xml или скрипт сборки Gradle.
  • Нажмите на кнопку ОК.

Импорт существующего проекта

Форматы проектов

IntelliJ поддерживает два типа формата проекта: один – на основе каталогов, а другой – на основе файлов . Формат на основе каталогов является более новым, рекомендуется. По умолчанию IntelliJ создает каталог проекта на основе формата. Вы можете выбрать формат проекта при создании нового проекта. В новом окне проекта просто нажмите на дополнительные настройки, как показано на рисунке ниже –

Форматы проектов

Директивный формат проекта

Этот формат помогает создать папку идей в вашем проекте и сохранить все файлы конфигурации в этой папке. Настройки сгруппированы в XML-файлы. Например, он создаст misc.xml, modules.xml, workspace.xml и так далее. Следующий скриншот поможет вам понять, как это работает –

Директивный формат проекта

Файловый формат проекта

Он создаст два файла проекта с расширениями ..ipr и wpr . Файл ipr будет содержать параметры, относящиеся к проекту, а файл wpr будет содержать параметры, относящиеся к рабочей области.

Файловый формат проекта

Чтобы преобразовать файловый проект в проект на основе каталога, перейдите в Файл → Сохранить как формат на основе каталога .

На основе каталогов против файлового формата проекта

По сравнению с форматом проекта на основе файлов формат проекта на основе каталога хранит настройки в отдельной папке со значимыми именами. Другие отличия –

Связанные настройки, сохраняемые в одном файле, упрощают управление в формате проекта на основе каталога.

Если папка содержит подпапку идеи, то IntelliJ распознает этот проект. Из-за этого вам не нужно явно выбирать проект ipr.

Формат проекта на основе каталогов разбивает настройки на несколько файлов, поэтому проще выбрать конкретный тип настроек для хранения в системе контроля версий.

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

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