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 or Test Sources Root
in 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.
Convert directories with java files to java modules in intellij
I recently switched to using IntelliJ. I manually imported some projects and I guess I didn’t do it correctly. They are all supposed to be java modules but they are just regular directory folders. Is there a way to convert them to java modules so I can run the programs or will I have to manually recreate new modules?

![]()
4 Answers 4
If you get the directory from some version system and it has a maven pom.xml configuration file, here’s a solution:
Find the pom.xml in the directory.
Right click the pom.xml .
Then you can see the popup windows. Select the last item «add as maven project file» .
Then, the maven build tool can automatically discern the directory as an module and import the specified jar dependencies.
![]()
There are a few ways to handle this. If your project has an existing build framework such as gradle, maven, etc, generally you can navigate to
File > New > Project From Existing Sources.
And then navigate to the gradle.build, pom.xml, or other framework specific build. When this project is created, all of the necessary source files should be properly identified.
Alternatively, you can also manually set the source directories by selecting the directory in the Project window, right clicking and selecting Mark Directory As > Sources Root .
![]()
You should mark this folder as source directory in project settings or with right-click on folder.
Как в IntelliJ IDEA в проекте в директории src создать поддиректории?
Начинаю осваивать Java c IDE от JetBrains по видеоурокам.
В этом видео https://youtu.be/xvUFqDKIKJE?t=685 представлена структура папок в проекте src > main > java > Start.java

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

Почему так и как это исправить?
- Вопрос задан более года назад
- 5227 просмотров
Простой 1 комментарий
- Вконтакте
- Вконтакте

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

Добрый день.
Прежде всего желаю вам успехов в изучении Java.
В Java мы оперируем не директориями, а пакетами (Package), хоть по сути пакеты и являются директориями.
Как добавить неисходные папки в проект IntelliJ IDEA
Недавно настроил многомодульный проект в IntelliJ со следующей структурой:
Я настроил module1 + 2 и веб-модуль как модули в IntelliJ, чтобы они отображались, но как сделать так, чтобы папка sql и lib отображалась на панели проекта? Они также должны быть включены в VCS, но IntelliJ их игнорирует. Как вы добавляете папки вне модулей в проект?
Скриншот проекта и проводника:

Используйте Добавить корень содержимого кнопка в модуле Sources таб. — CrazyCoder
Но это контент, связанный с проектом, для них нет подходящего модуля — Rasmus Franke
Для тех, кто переходит на eclipse, просто создайте свой проект из существующих источников, а затем выберите «Импорт из eclipse». Все найдет. Раньше я просто создавал как не-затмение. Надеюсь, это поможет кому-то в той же лодке, что и я. Eclipse ужасен с точки зрения сохранения правильных сочетаний клавиш, и это меня раздражало. Вернемся к любви к IJ. — killjoy
5 ответы
Это не строгий ответ на вопрос, но у меня это сработало, поэтому я публикую, возможно, кому-то это будет полезно.
Если вы хотите добавить произвольную папку в свой проект (даже из другого места, чем ваши проекты), просто добавьте его как модуль. Вам не нужно так сильно беспокоиться о типе, например, мне нужно было добавить папку с некоторыми сценариями SQL, я добавил ее как модуль Java, и она хорошо видна в IntelliJ, даже если она не имеет структуры maven или исходников Java.
Вот как это сделать:
- Файл> Структура проекта> Модули
- Добавить > Новый модуль > . (например, модуль Java)
- В настройках нового модуля отметьте подпапки, которые вы хотите видеть, как «Источники».
ответ дан 03 авг.
Действительно очень полезно! Intellij в этом вопросе довольно запутан. — тобик
именно то, что я искал, спасибо — демиан
Кажется, работает только в том случае, если модуль имеет только исходные файлы Java. — SDM
@sdm на момент написания вышеуказанного сообщения определенно работал с файлами, отличными от Java (как упоминалось в моем случае SQL). На самом деле я только что попробовал этот подход с Intellij Community Edition 2017.3.4, и он все еще работал для меня. — машины
Да, я думаю, что проблема немного нюансирована. Если я хочу добавить случайную папку с некоторым кодом Java, она выберет только папку, содержащую исходный код Java, в качестве исходной папки. — SDM
Это то, что я обычно вижу при создании проекта из существующих модулей. Все модули будут отображаться в проекте, но не в других каталогах, связанных с проектом. Этими каталогами могут быть файлы конфигурации, сценарии среды или пакеты сценариев SQL, которые не вписываются в тип модуля Intellij.
Чтобы показать остальные исходные файлы и каталоги проекта, я создаю родительский модуль из корня проекта.
- Создайте новый модуль, используя знак +. Новый модуль может быть любого типа (я использую java).
- На Далее экран установить Корень содержимого и Расположение файла модуля в корневую папку проекта.
- Выбрать Завершить
Все ваши другие модули теперь должны быть подмодулями корня, и теперь должны отображаться другие ваши файлы проекта.
ответ дан 10 мар ’16, в 20:03
Добавление и удаление корней содержимого
Чтобы добавить новый корень содержимого:
- Перейти к файлу | Структура проекта или нажмите Ctrl+Shift+Alt+S.
- Выберите «Модули» в разделе «Настройки проекта».
- Выберите нужный модуль, а затем откройте вкладку Источники в правой части диалога.
- Щелкните Добавить корневой каталог содержимого.
- Укажите папку, которую вы хотите добавить в качестве нового корня содержимого, и нажмите OK.

ответ дан 21 апр.
я использовал File -> New -> Module from Existing Sources.

Затем я просто выбираю папку и добавляю ее.

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

Ваш проект должен выглядеть так (дерево представления проекта):
И в этом случае вы обязательно должны увидеть остальные папки. У меня есть пример проекта, где это работает.
Из вашего снимка экрана я предполагаю, что вам не хватает корневого каталога (корень проекта не такой, как вы ожидали). Я добавил еще один скриншот. Для ваших 3 модулей должна быть одна корневая папка. На вашем скриншоте этого нет. У вас есть 3 отдельные папки без общей корневой папки. В MacOs корень проекта отображается в заголовке окна. В моем случае это указывает на
/devel/sandbox . Я думаю, вы должны попытаться создать новый проект для этого trunk папка. С нуля. Затем добавьте существующие модули, и все будет в порядке?!

ответ дан 30 авг.
Однако они не появляются. Один файл отображается вне папок модуля, файл свойств в корне проекта. Поэтому я думаю, что корень проекта должен быть настроен правильно. Должен ли я иметь какой-то файл проекта в корне моего проекта или достаточно папки .idea? — Расмус Франке
Компания .idea папка заменяет старые файлы проекта (.ipr, .ipw). В каждом модуле должны быть файлы .iml. Вот и все. Можете ли вы добавить скриншот из вашей IDE и файловой системы этого корня проекта? — маны
@mana, если я правильно вас понял, если мне нужен корень проекта с тремя модулями, действительно ли мне нужны ЧЕТЫРЕ модуля («корневой» модуль с тем же корнем, что и корень проекта, и три модуля под ним)? Я создал проект, создал три модуля в корне проекта, и я не видел никаких других папок в корне проекта. Только когда я создал корневой модуль с тем же корнем, что и корень проекта, я смог увидеть дополнительные папки. — пользователь138439
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками intellij-idea or задайте свой вопрос.