I have cloned a spring boot project from GitLab having multiple branches in IntelliJ. I checkout to the branch in which I want to work. But I am getting «Java file outside of source root» on all the files. Please suggest what I am doing wrong. I just installed IntelliJ and it’s the first project that I am importing.
asked Aug 21, 2020 at 10:34
1,067 1 1 gold badge 11 11 silver badges 15 15 bronze badges
What build system is used? Gradle? Maven? SBT? Make sure you’ve enabled the corresponding plugin in your IDE.
Aug 21, 2020 at 10:36
@JoachimSauer I am using Maven. I tried to build a project and it is building successfully. But still facing the same problem. I just installed IntelliJ and it’s the first project that I am importing
Aug 21, 2020 at 10:37
IntelliJ has a Maven plugin installed by default and (I think) enabled as well, so if you just import the project it should detect all the relevant source paths, unless the maven build does some unusual things . Check this document as you didn’t give us a lot of information on how you imported the project.
Aug 21, 2020 at 11:31
@JoachimSauer I imported the Gitlab project by selecting the option «import from git» and pasting the repo link.
Aug 21, 2020 at 11:33
@Abhishek The error message «file outside of source root» hints, that your source root (and/or the files location) may be wrong. The source root should be the java folder within src folder. Right click on java folder and choose [mark directory as] > sources root. If that not helps can you pls provide us the github link and branch you worked or a minimal simple working example. Also pls provide us the complete error with stacktrace info.
Aug 21, 2020 at 20:39
34 Answers 34
If you do an ‘import from git’, IntelliJ doesn’t import the project structure from maven (or gradle) automatically.
One way to do this afterwards is to right-click on the pom.xml file in the root directory, and select ‘Add as maven project’. Then the folders will be marked correctly, and dependent libraries will be imported. There should be no need to mark individual source folders manually.
I prefer to do a git clone outside of IntelliJ, and afterwards open the project in IntelliJ from the local filesystem, then IntelliJ imports the maven project structure automatically.
answered Sep 23, 2020 at 8:07
16.7k 3 3 gold badges 38 38 silver badges 61 61 bronze badges
I cannot find ‘Add as maven project’ on right clicking the pom.xml file.
Aug 9, 2023 at 18:54
Very simple solution: —
Click on «maven» on the right toolbar in IntelliJ and then click on the refresh button.
answered Oct 13, 2020 at 17:37
Hokkyokusei Hokkyokusei
1,091 13 13 silver badges 18 18 bronze badges
This solution fits good for files from «target — generated-sources». Thanks!
Feb 20, 2021 at 9:48
perfect..short and sweet — thank you.
Apr 23, 2022 at 19:05
works as well for Gradle project
Aug 29, 2022 at 14:10
After the maven refresh, I had to ‘Invalidate Caches and Restart’ Intellij IDEA.
Nov 28, 2022 at 22:32
This has been driving me quite mad and I am a newbie as well. I finally solved it by using:
file > project structure >
Then going to Modules and removing all the files from the root using the x marks on the far right. I then used the +Add Content Root to reselect the src folders that contained my .java and hit Apply. Finally InteliJ sees the files as in the project and the folders gain the blue square on the main view.
Java file outside of source root – quick fixes
“Java file outside of source root” is a common error message in IntelliJ IDEA. It simply said that you need to add the file to the project root before doing anything.
For those who are beginning with Java, the error might become a little trouble. In this short article, we will list a few quick fixes for “Java file outside of source root”.
Import the module from pom.xml for Maven projects
If you’re working on a Maven project, you would have to import import the module from pom.xml so that it configures the roots automatically.
Sources root is marked in blue in the project view. Here is the example of the properly configured project.
Maven roots will be configured following its Standard Directory Layout, which Maven expects from a regular project.
In order to add a Maven module to the project in which you are already working.
In the Project tool window, right-click the project folder and select New > Module. Alternatively, from the main menu, select File > New > Module to open the New Module wizard.
If you used main menu to add a module then the process of adding a module is the same as Creating a new Maven project. If you are adding sub modules by right-clicking the root folder then the process of adding a new module is shorter. You need to specify the name of your module in the Name field. The rest of the information is added automatically and you can use either the default settings or change them according to your preferences.
Manually mark a folder as source root
Alternatively, you can manually set a folder to be the source root from the sidebar of IntelliJ.
Simply right click on the src folder and select “Mark Directory as” > “Sources Root”.
You can also do this by configuring project modules:
Open file->Project Structure , select Modules.
Select the src folder and choose Sources in the Mark as section, then click Apply, which solves the problem of Source Root.
Regenerate Maven Sources and Update Folders
If you are using Maven and Intellij Idea does not include generated sources folder automatically, the following option works in majority of the cases.
Right click on your project
Choose Maven >Generate sources and update folders
Alternatively, you can use the Maven sidebar and click on the folder with spinner icon to activate Generate Sources and Update Folders for All Projects.
If none of the above solutions worked, here’s a few more suggestions:
Move the Java files into the source code root directory. This may require updating your project configuration or build tools settings accordingly.
Add the Java file to your project source file path. This can be done in the configuration file of the project build tool (such as Maven or Gradle) or in the project settings in the IDE. Make sure you have all required libraries and dependencies in your classpath.
Change the Java compiler options to allow the compiler to look for Java files in non-standard source root directories. For example, when using the javac command, you can use the -sourcepath option to specify the location of your source files.
If you must keep your Java files outside of your Java files, make sure they are in the correct directory structure with the correct package names and import statements. Also, make sure your compiler or IDE is configured with the correct classpath and environment with all required libraries and dependencies.
Having read to the end of this article, it is clear that you’re getting started with Java. In that case, No string-argument constructor/factory method to deserialize from string value is another common error in Spring Framework which you might find interesting to find out more about.
Content roots
Content in IntelliJ IDEA is a group of files that contain your source code, build scripts, tests, and documentation. These files are usually organized in a hierarchy. The top-level folder is called a content root .
Modules normally have one content root. You can add more content roots. For example, this might be useful if pieces of your code are stored in different locations on your computer.
At the same time, modules can exist without content roots. In this case, you can use them as a collection of dependencies for other modules.
The content root directory in IntelliJ IDEA is marked with the icon.
Configure folder structure
Folders within a content root can be assigned to several categories depending on the content that they keep.
In the Project tool window ( Alt+1 ), right-click a folder and select Mark Directory as .
Select the necessary category.
This way you can assign categories to subfolders as well.
To restore the previous category of a folder, right-click this folder again, select Mark Directory as , and then select Unmark as . For excluded folders, select Cancel Exclusion .
You can also configure folder categories in Project Structure | Modules | Sources .
Folder categories
Sources This folder contains production code that should be compiled. IntelliJ IDEA compiles the code within the Sources folder. Do not place configuration files (the .idea folder or its content and the .iml file) to this folder. For more information about different types of settings, refer to Project, module, and global settings.
Generated Sources The IDE considers that files in the Generated Sources folder are generated automatically rather than written manually, and can be regenerated.
Test Sources These folders keep code related to testing separately from production code. Compilation results for sources and test sources are normally placed into different folders.
Generated Test Sources The IDE considers that files in this folder are generated automatically rather than written manually, and can be regenerated.
Resources (Java only) Resource files used in your application: images, configuration XML and properties files, and so on. During the build process, resource files are copied to the output folder as is by default. You can Change the output path for resource files in your project. Similarly to sources, you can specify that your resources are generated. You can also specify which folder within the output folder your resources should be copied to.
Test Resources These folders are for resource files associated with your test sources.
Excluded Files in excluded folders are ignored by code completion, navigation and inspection. That is why when you exclude a folder that you don’t need at the moment, you can increase the IDE performance. Normally, compilation output folders are marked as excluded. Apart from excluding the entire folders, you can also exclude specific files. Marking folders as excluded doesn’t affect deployment. For more information about excluding files from deployment, refer to Exclude files and folders from uploading and downloading.
Add a new content root
Go to File | Project Structure Control+Alt+Shift+S and click Project Settings | Modules .
Select the necessary module and then open the Sources tab in the right-hand part of the dialog.
Click Add Content Root and specify the folder that you want to add as a new content root.
To remove a content root, click the Remove content entry button (). IntelliJ IDEA marks the selected root as a regular folder. The folder itself and its contents will not be deleted.
Exclude files and folders
Exclude files
Java files and binaries cannot be excluded.
If you don’t need specific files, but you don’t want to completely remove them, you can temporarily exclude these files from the project. Excluded files are ignored by code completion, navigation, and inspections.
To exclude a file, you need to mark it as a plain text file. You can always return excluded files to their original state.
Right-click a file in the Project tool window ( Alt+1 ).
Select Override File Type | Plain text . Plain text files are marked with the icon.
To revert the changes, right-click the file and select Revert File Type Override . from the menu.
Exclude folders
Right-click a folder in the Project tool window ( Alt+1 ).
Select Mark Directory as | Excluded . Excluded folders are marked with the icon.
To restore the previous category of a folder, right-click this folder again, select Mark Directory as , and then select Cancel Exclusion .
Exclude files and folders by name patterns
In some cases, excluding files or folders one by one is not convenient. For example, this may be inconvenient if your source code files and files that are generated automatically (by a compiler, for instance) are placed in the same directories, and you want to exclude the generated files only. In this case, you can configure one or several name patterns for a specific content root.
If a folder or a filename located inside the selected content root matches one of the patterns, it will be marked as excluded. Objects outside the selected content root won’t be affected.
All files within excluded folders will be excluded as well.
Go to File | Project Structure , or press Control+Alt+Shift+S .
Click Modules under the Project Settings section, and then select a module. If there are several content roots in this module, select the one that you want to exclude files or folders from.
In the Exclude files field located at the bottom of the dialog, enter a pattern. For example, enter *.aj *_test.go to exclude AspectJ files. You can configure multiple patterns and separate them with the semicolon symbol ( ; ).
Marking folders as excluded doesn’t affect deployment. For more information about excluding files from deployment, refer to Exclude files and folders from uploading and downloading.
Assign a package prefix to Java sources
In Java, you can assign a package prefix to a folder instead of configuring a folder structure manually. A package prefix can be assigned to source folders, generated source folders, test source folders and generated test source folders.
In the main menu, go to File | Project Structure Control+Alt+Shift+S and click Modules .
Select the necessary module and open the Sources tab.
In the right-hand pane, click next to Source Folders or Test Source Folders .
Specify the package prefix and click OK .
Change the output path for resources
When you’re building a project, the resources are copied into the compilation output folder by default. You can specify a different directory within the output folder to place resources.
This information is valid for projects that are built with the native IntelliJ IDEA builder. If you’re using a build tool, such as Maven or Gradle, make all changes using the build file.
In the main menu, go to File | Project Structure Control+Alt+Shift+S and click Modules .
Select the necessary module and open the Sources tab.
In the right-hand pane, under Resource Folders or Test Resource Folders , click to the right of the necessary folder (folder path).
Specify the path relative to the output folder root, and click OK .
Проблема с классами после создания Maven проекта
Привет, на Java я новичок, делала проект изначально без Maven, потом решила сделать из него Maven проект (учусь как), добавила в корень pom.xml , в Intellij Idea указала, что хочу сделать его maven проектом, и вот проблема — после этого классы как будто не видят друг друга. До этого работало нормально, все запускалось. И что самое странное в Edit Configurations не видит класса Main в модуле проекта. Заранее благодарю за ответы. P.S. Содержание pom.xml , после идет описание локального репозитория и зависимостей. Сам файл лежит в той же папке, что и src. Класс Main в папке src/main/java , а в подпапках и рядом с Main.java еще есть другие классы, которые используют друг друга. Так вот они друг друга и не видят. И еще не находит метод main в main.java.Main
Пальцем в небо: проверьте, где лежат ваши исходники. По умолчанию Maven будет искать их в папке src/main/java (относительный путь от pom.xml ). А вообще, добавьте в вопрос больше информации о вашей проблеме (расположение исходников, содержимое pom.xml , сообщения об ошибках), попытайтесь создать минимальный воспроизводимый пример.
22 янв 2018 в 9:33
Ой извините, вот содержание pom.xml
22 янв 2018 в 9:59
Закройте IDEA, удалите директорию .idea в корне проекта и импортируйте проект в IDEA, как Maven проект.
22 янв 2018 в 10:59 должен быть указан название вашего проекта
22 янв 2018 в 11:14
1 ответ 1
Сортировка: Сброс на вариант по умолчанию
Судя по main.java.Main , вы решили, что папки main/java являются частью иерархии пакетов. Нет, они не являются. В проектах Maven вершина иерархии пакетов находится в папке src/main/java . Если ваш класс Main лежит в src/main/java/Main.java , то он находится в корневом пакете. То есть, в pom.xml на него можно ссылаться как Main (а не main.java.Main ), а в Main.java не должно быть строчки package main.java; . Аналогичная ситуация с объявлением пакета в остальных классах.
UPDATE
Собственно, то, что я написал выше, и есть решение вашей проблемы, просто вы его его как-то выборочно применили. Ещё раз: main.java не является частью иерархии пакетов. Это стандартная папка с исходниками приложения, с которой эта иерархия и начинается. У вас же в каждом классе есть объявление package main.java , хотя ни один ваших из классов в этом пакете не находится. Например, класс Solution в вашем коде объявлен как находящийся в пакете main.java.Functions.FunctionsSolutions , хотя по факту он находится в пакете Functions.FunctionsSolutions . Исправьте пакеты всех классов, поправьте импорты, и классы начнут видеть друг друга.
И ещё совет не по теме: в Git обычно хранят только исходники. Там не должно быть ничего, что другой разработчик не смог бы получить самостоятельно, скомпилировав проект. То есть, ни скомпилированных классов (папки out и target , их можно получить, скомпилировав проект), ни библиотек (папка lib , её содержимое должен скачивать Maven) в Git быть не должно. Также обычно в Git не хранят настройки IDE (папка .idea , файлы *.iml ). Их можно исключить из контроля версий при помощи файла .gitignore .