171
votes

I have looked around quite a bit and haven't found the best solution to convert an existing IntelliJ project to Gradle. I work in a team environment and we currently share the .ipr file as we have a few build configurations that we track. We will be getting rid of those in favor of Gradle eventually but I can't screw things up too much until the Gradle conversion is done.

Also, our Java source files are located in the root of the src directory instead of src/main/java as is standard.

Is there a way I can add Gradle to my project that won't make me delete and recreate my IntelliJ project and won't screw everyone else up when they do a Git pull?

8
To answer the question of your source directory - you need to override the default source directory with sourceSets. See how we did this in the MongoDB Java driver: github.com/mongodb/mongo-java-driver/blob/… - Trisha

8 Answers

215
votes

Add:

build.gradle 

in your root project folder, and use plugin for example:

apply plugin: 'idea'
//and standard one
apply plugin: 'java'

and with this fire from command line:

gradle cleanIdea 

and after that:

gradle idea

After that everything should work

76
votes

There is no need to remove any .iml files. Follow this:

  • close the project
  • File -> Open... and choose your newly created build.gradle
  • IntelliJ will ask you whether you want:
    • Open Existing Project
    • Delete Existing Project and Import
  • Choose the second option and you are done
47
votes

Another way, simpler.

Add your

build.gradle

file to the root of your project. Close the project. Manually remove "*.iml" file and/or ".idea" directory. Then choose "Import Project...", navigate to your project directory, select the build.gradle file and click OK.

21
votes

In IntelliJ 2017.2.4 I just closed the project and reopened it and I got a dialog asking me if I wanted to link with build.gradle which opened up the import dialog for Gradle projects.

No need to delete any files or add the idea plugin to build.gradle.

16
votes

Just as a future reference, if you already have a Maven project all you need to do is doing a gradle init in your project directory which will generates build.gradle and other dependencies, then do a gradle build in the same directory.

7
votes

I'm using Version 12 of IntelliJ.

I solved a similar problem by creating an entirely new project and "Checking out from Version Control" Merging the two projects later was fairly easy.

3
votes
  1. Add build.gradle in your project's root directory.

  2. Then just File -> Invalidate Caches / Restart

Here is a basic build.gradle for Java projects:

plugins {
    id 'java'
}

sourceCompatibility = '1.8'
targetCompatibility = '1.8'
version = '1.2.1'
0
votes

To add to other answers. For me it was helpful to delete .mvn directory and then add build.gradle. New versions of IntelliJ will then automatically notice that you use Gradle.