Вопрос №19676 от пользователя Артем Никитин в проекте «Казино»
В Intellij Idea при создании проекта создается папка src, которая автоматом помечается Sources Root. В итоге в папке src вместо директорий автоматом создаются пакеты. Для того, чтобы повторить требуемую структуру директорий/пакетов пришлось убрать отметку Sources Root с папки src. В результате при попытке коммита файла Slot.java Intellij Idea выдает 2 ошибки: Cannot resolve symbol ‘String’, Cannot resolve symbol ‘System’. Для того, чтобы избавиться от этих ошибок пришлось пометить в качестве Sources Root папку java. На мой взгляд это не совсем правильное решение, но другого варианта я не нашел.
Напротив — это совершенно правильное решение. Более того — именно так и сделает IDEA на следующем шаге — когда мы воспользуемся Maven`ом. Это не совсем инструментальный проект — помимо простой рекомендации, мы здесь не акцентируем внимание на «фишках» IDEA’и, так что было бы не совсем корректно здесь приводить ещё и инструкцию, как настраивать проект в ней, хотя, возможно, и стоит написать на это счёт отдельную статью или даже курс и дать здесь на него ссылку. Я подумаю, спасибо!
Java file outside of source root intelliJ
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.
Best Solution
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 open the project from the local filesystem, then IntelliJ imports the maven project structure automatically.
Ошибка Intellij IDEA: Java file outside of source root
Всем привет. Пару месяцев назад писал один проект , но из-за его сложности (для меня , на тот момент)я его забросил . И вот спустя продолжительный отрезок времени возвращаюсь к нему и не могу его скомпилировать т.к рядом с классами написано :» Java file outside of source root». Посмотрел на иностранных форумах схожие проблемы , но решения не нашел . И вот я прошу вас помочь мне с моей проблемой . (Ранее писал на Eclips пару дней назад перешел на Intellij IDEA. В эклипсе с подобными ошибками не сталкивался. Компилятор — maven, кстати в прошлых проектах в IDEA была справа на панели кнопка «мавена», но конкретно в этом обсуждаемом проекте ее нет. )
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
Ответы с готовыми решениями:
Groovy+Java: семантическая ошибка при компиляции в Intellij Idea 14.0.2
Всем привет! При компиляции выползает такое вот: Error:Groovyc: BUG! exception in phase.
Intellij Idea — Supported source version ‘RELEASE_6’ from annotation processor
В среде разработки Intellij Idea 2019 появляется сообщение Что это значит и как от него.
Intellij Idea Jar file generation fault
Пытаюсь собрать исполняемый (JAR) файл из примеров: org.eclipse.paho.client.mqttv3.Mqtt* import.
Java intellij idea
Здравствуйте. Буду рад ответу, как в intelij idea найти класс system? И еще, в java все библиотеки.
Проект Java в IntelliJ IDEA
При попытке скомпилировать проект выходит ошибка Exception in thread "main".
Java file outside of source root intelliJ
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,027 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.5k 3 3 gold badges 37 37 silver badges 61 61 bronze badges
I cannot find ‘Add as maven project’ on right clicking the pom.xml file.
Aug 9 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,051 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
I fixed it using this way:
File > Project Structure > Modules > Sources
and then marked java files dir as Sources.
3,146 7 7 gold badges 32 32 silver badges 38 38 bronze badges
answered Nov 21, 2020 at 12:17
Sunny Gupta Sunny Gupta
749 8 8 silver badges 7 7 bronze badges
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.