675

So I have tried to add my local .jar file dependency to my build.gradle file:

apply plugin: 'java'

sourceSets {
    main {
        java {
            srcDir 'src/model'
        }
    }
}

dependencies {
    runtime files('libs/mnist-tools.jar', 'libs/gson-2.2.4.jar')
    runtime fileTree(dir: 'libs', include: '*.jar')
} 

And you can see that I added the .jar files into the referencedLibraries folder here: https://github.com/WalnutiQ/wAlnut/tree/version-2.3.1/referencedLibraries

But the problem is that when I run the command: gradle build on the command line I get the following error:

error: package com.google.gson does not exist
import com.google.gson.Gson;

Here is my entire repo: https://github.com/WalnutiQ/wAlnut/tree/version-2.3.1

Wang-Zhao-Liu Q
  • 12,331
  • 27
  • 70
  • 106
  • Are you sure about runtime instead of compile? compile files (....) – Gabriele Mariotti Dec 20 '13 at 09:22
  • 3
    it looks like it is compile dependency if jar can't be built. try: compile files('libs/mnist-tools.jar', 'libs/gson-2.2.4.jar') if you still have a problem then try absolue paths becouse that also might be issue. – patrz jaka franca Dec 20 '13 at 09:28
  • 1
    This [Stack Overflow question](http://stackoverflow.com/questions/16608135/android-studio-add-jar-as-library) finally gave me the answer I needed. – craned Oct 16 '14 at 19:52

17 Answers17

789

According to the documentation, use a relative path for a local jar dependency as follows:

dependencies {
    implementation files('libs/something_local.jar')
}
Dave Jarvis
  • 28,853
  • 37
  • 164
  • 291
leeor
  • 14,718
  • 5
  • 28
  • 58
  • 9
    @Gubatron it's documented now: http://www.gradle.org/docs/current/userguide/dependency_management.html#sub:file_dependencies – David Moles Jan 12 '15 at 22:23
  • 7
    just wanted to add that for those who are using relative paths to our jar: dependencies { compile files("libs/something_local.jar" } (i.e. double-quotes not single-quotes) are needed by Groovy to evaluate the path. Single-quotes are taken literally in Groovy. – specialk1st Mar 23 '16 at 03:05
  • So I am using the same thing and I get compilation error (looks like it does not find the jar there.) If I give absolute path it works fine. – RV_Dev Jun 06 '17 at 13:51
  • I would prefer this solution, but I have found that if the file doesn't exist, no error is outputted by Gradle. I have found this personally, See this SO question for details: https://stackoverflow.com/q/42527631/4851565 – entpnerd Aug 08 '17 at 23:46
  • i was getting a similar error even after using this solution. Mistake i did put libs folder under apps not in same level as apps – Rishabh Dugar Aug 26 '17 at 14:01
  • Note that - if you have external dependencies in your jar, you have to build a shadow jar to be able to use it this way, however, if you publish it to your local maven repo it's unnecessary. – wieczorekm Jul 02 '18 at 12:07
503

If you really need to take that .jar from a local directory,

Add next to your module gradle (Not the app gradle file):

repositories {
   flatDir {
       dirs 'libs'
   }
}


dependencies {
   implementation name: 'gson-2.2.4'
}

However, being a standard .jar in an actual maven repository, why don't you try this?

repositories {
   mavenCentral()
}
dependencies {
   implementation 'com.google.code.gson:gson:2.2.4'
}
AMK
  • 322
  • 2
  • 11
Jorge_B
  • 9,144
  • 2
  • 14
  • 22
  • 5
    I came looking for exactly this, but I found that my local repository does not resolve transitive dependencies.(Gradle 2.7, example POM is com.mojang:authlib:1.5.21 as extracted by minecraftforge.net) – Karl the Pagan Oct 20 '15 at 03:24
  • 1
    If you have local jar files in multiple directories, you need to add all of them to the flatDir. Ex :- flatDir { dirs 'libs1','libs2','libs3'} – Dhumil Agarwal Jun 08 '16 at 05:47
  • I saw some other options below, they don't suit my use-case. Most builds are Maven based just one or two handy libs need to be referenced. In my case ... `dirs '/projects/lib/java'`. I would prefer some option to get Maven or a related tool to _bag_ such creatures until-such-time as folk save them in a repository ;-) – will Aug 25 '16 at 13:19
  • 13
    I am having a `gradle.build` file - What is these "app gradle file" and the "module gradle"? – Lealo Oct 10 '17 at 00:31
  • What if my jar is based in Gradle, not Maven? – Alex78191 Apr 18 '18 at 19:20
  • 2
    Any chance someone will update the answer with a link to the official Gradle documentation section describing these features? – kuza Jun 28 '18 at 07:17
  • How to apply this using Kotlin DSL? `compile name: 'gson-2.2.4'` – Eng.Fouad Dec 13 '18 at 06:56
  • 2
    `implementation(":gson:2.2.4")` seems to be the way to do it. – Eng.Fouad Dec 13 '18 at 07:25
  • 1
    Instead of `implementation name:'local-lib-4.1.2-876'` I could also use `implementation name: 'local-lib', version: '4.1.2-876'` – Tarnschaf Feb 03 '20 at 17:03
  • Doesn't work with Spring Boot plugin bootJar task. Solution below did work https://stackoverflow.com/a/20956456/1307586 – volkovs Apr 22 '20 at 12:09
339

You could also do this which would include all JARs in the local repository. This way you wouldn't have to specify it every time.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}
Nightwolf
  • 4,060
  • 2
  • 18
  • 26
  • 3
    This is used for compiling all the jars in lib directory. Its the perfect solution (y) – Sheraz Ahmad Khilji Sep 22 '15 at 17:57
  • 1
    ...unless you plan to share that libs directory with different modules having different sets of dependencies, such as not putting server code in with client code, or having more than one version of a dependency in different sub-module. – Ajax Aug 27 '16 at 11:12
  • This is my preferred implementation over the accepted answer because it explicitly states the location of the files. It's useful for when you refer to a repository such as mavenCentral for some libraries and local copies for others. In that case there may be a lag while gradle searches for the local libraries in the other repositories. – satbot Oct 11 '17 at 06:26
  • 2
    Note that dir can be an absolute path as well. Also instead of 'include' I had to use 'includes'. – eriel marimon Dec 08 '17 at 16:36
  • 1
    for gradle 7+ go with `implementation fileTree(dir: 'lib', includes: ['*.jar'])` (or `api`, depending on your needs) – m02ph3u5 Apr 21 '21 at 14:03
58

The following works for me:

compile fileTree(dir: 'libs', include: '*.jar')

Refer to the Gradle Documentation.

Frits
  • 6,116
  • 10
  • 39
  • 50
Misha
  • 773
  • 1
  • 8
  • 13
  • important to remember that is this method if you don't want specific library to compile with your project you will have to remember to delete it from libs folder...i don't like this method because i don't see which library i added unless i enter to the library – Jesus Dimrix Sep 19 '17 at 13:04
  • 2
    How is this different than @Nightwolf's answer? – Trenton Oct 16 '17 at 06:55
  • 2
    Could not find method compile() for arguments [directory 'libs'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler – ieXcept May 29 '19 at 09:46
  • How can I reach a specific module's folder? I want to add a dependency to "app" module, to reach on some aar file on another module's folder. Meaning: `library/build/outputs/aar/library-release.aar` – android developer Mar 10 '21 at 10:53
39

You can try reusing your local Maven repository for Gradle:

  • Install the jar into your local Maven repository:

    mvn install:install-file -Dfile=utility.jar -DgroupId=com.company -DartifactId=utility -Dversion=0.0.1 -Dpackaging=jar

  • Check that you have the jar installed into your ~/.m2/ local Maven repository

  • Enable your local Maven repository in your build.gradle file:

    repositories {
      mavenCentral()  
      mavenLocal()  
    }
    
    dependencies {  
      implementation ("com.company:utility:0.0.1")  
    }
    
    • Now you should have the jar enabled for implementation in your project
AMK
  • 322
  • 2
  • 11
Daniel Mora
  • 2,379
  • 1
  • 21
  • 19
  • This one helped me when all else failed! – User3 Oct 17 '17 at 12:18
  • While this works, this is a work around and should not be used in automated production/stage environment since this adds an additional dependency of having a .m2 folder (maven installation) in the build system. – saurav.varma Apr 16 '18 at 08:24
  • When I tried this, I get an error: could not parse POM, already seen doctype. This is when I try to run a gradle command. – SledgeHammer Dec 05 '20 at 00:03
31

The accepted answer is good, however, I would have needed various library configurations within my multi-project Gradle build to use the same 3rd-party Java library.

Adding '$rootProject.projectDir' to the 'dir' path element within my 'allprojects' closure meant each sub-project referenced the same 'libs' directory, and not a version local to that sub-project:

//gradle.build snippet
allprojects {
    ...

    repositories {
        //All sub-projects will now refer to the same 'libs' directory
        flatDir {
            dirs "$rootProject.projectDir/libs"
        }
        mavenCentral()
    }

    ...
}

EDIT by Quizzie: changed "${rootProject.projectDir}" to "$rootProject.projectDir" (works in the newest Gradle version).

centic
  • 14,264
  • 6
  • 58
  • 113
Big Rich
  • 5,364
  • 37
  • 59
28

A solution for those using Kotlin DSL

The solutions added so far are great for the OP, but can't be used with Kotlin DSL without first translating them. Here's an example of how I added a local .JAR to my build using Kotlin DSL:

dependencies {
    compile(files("/path/to/file.jar"))
    testCompile(files("/path/to/file.jar"))
    testCompile("junit", "junit", "4.12")
}

Remember that if you're using Windows, your backslashes will have to be escaped:

...
compile(files("C:\\path\\to\\file.jar"))
...

And also remember that quotation marks have to be double quotes, not single quotes.


Edit for 2020:

Gradle updates have deprecated compile and testCompile in favor of implementation and testImplementation. So the above dependency block would look like this for current Gradle versions:

dependencies {
    implementation(files("/path/to/file.jar"))
    testImplementation(files("/path/to/file.jar"))
    testImplementation("junit", "junit", "4.12")
}
Jonathan Landrum
  • 1,861
  • 2
  • 25
  • 39
  • 1
    +1 worked for me! Do you know how to do the same without having to produce the jar file (in case I happened to produce the jar)? – Kareem Jeiroudi May 16 '19 at 12:09
  • 2
    @KareemJeiroudi I may be misunderstanding your question, but if you are talking about making a module a dependency of the project, you would do something like this: `compile(project(":MyProject"))`, where "MyProject" is defined in your `settings.gradle` file with something like `include("MyProject")`. – Jonathan Landrum May 16 '19 at 15:19
14

A simple way to do this is

compile fileTree(include: ['*.jar'], dir: 'libs')

it will compile all the .jar files in your libs directory in App.

ZygoteInit
  • 455
  • 5
  • 9
  • Is fileTree works for all subdirectories in the libs folder. Example few jars inside the libs/sping/spring.jar, in this case does it include the spring .jar also? – mgr Jun 27 '16 at 12:52
  • No, it doesn't. Technically it shouldn't as well, as we are giving the 'dir:libs' not subdirectories of libs. – ZygoteInit Jun 28 '16 at 06:15
  • In this case how to get all the libraries from the subdirectories with minimum tasks (because our project contains so many subdirectories. – mgr Jun 28 '16 at 10:12
  • Hey @mallikgm sorry for late reply, did you tried adding wildcard in dir path like compile fileTree(include: ['*.jar'], dir: 'libs*') – ZygoteInit Jul 12 '16 at 05:53
  • 2
    How is this different than @Nightwolf's answer? – Trenton Oct 16 '17 at 06:53
  • I think this is the best solution. This is *already* in your `build.gradle` if you generated it using intellij "android" new project type – John Henckel Jan 17 '21 at 22:07
14

Shorter version:

dependencies {
    implementation fileTree('lib')
}
Topera
  • 11,264
  • 14
  • 59
  • 100
9

The Question already has been answered in detail. I still want to add something that seems very surprising to me:

The "gradle dependencies" task does not list any file dependencies. Even though you might think so, as they have been specified in the "dependencies" block after all..

So don't rely on the output of this to check whether your referenced local lib files are working correctly.

icyerasor
  • 4,305
  • 1
  • 35
  • 45
  • 1
    Wow I wish I read your answer 3 hours ago! Thanks. That's another real gotcha that the Gradle people threw in for us devs. – georgiecasey Jan 20 '21 at 22:06
8

I couldn't get the suggestion above at https://stackoverflow.com/a/20956456/1019307 to work. This worked for me though. For a file secondstring-20030401.jar that I stored in a libs/ directory in the root of the project:

repositories {
    mavenCentral()
    // Not everything is available in a Maven/Gradle repository.  Use a local 'libs/' directory for these.
    flatDir {
       dirs 'libs'
   }
}

...

compile name: 'secondstring-20030401'
Community
  • 1
  • 1
HankCa
  • 7,927
  • 7
  • 55
  • 72
  • thank you! no idea why but only this worked for me. made a 'libs' folder at my project root, shoved the .jar in there, and copied your 'compile name' entry. Dropped the .jar extension too of course. – anon58192932 Jul 19 '17 at 23:36
  • Nah, this doesn't work me Could not find :miglayout-core:. Searched in the following locations: file:/user/path/to/miglayout-core.jar – Well Smith Apr 14 '18 at 17:38
  • this work if you want add a file directory as repository : https://docs.gradle.org/current/userguide/repository_types.html#sec:flat_dir_resolver – Grubhart Feb 09 '19 at 01:28
6

The best way to do it is to add this in your build.gradle file and hit the sync option

dependency{
    compile files('path.jar')
}
pcsaunak
  • 151
  • 1
  • 9
6

The solution which worked for me is the usage of fileTree in build.gradle file. Keep the .jar which need to add as dependency in libs folder. The give the below code in dependenices block in build.gradle:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}
Jince Martin
  • 253
  • 1
  • 9
  • 17
3

You can add jar doing:

For gradle just put following code in build.gradle:

dependencies {
...
compile fileTree(dir: 'lib', includes: ['suitetalk-*0.jar'])
...
}

and for maven just follow steps:

For Intellij: File->project structure->modules->dependency tab-> click on + sign-> jar and dependency->select jars you want to import-> ok-> apply(if visible)->ok

Remember that if you got any java.lang.NoClassDefFoundError: Could not initialize class exception at runtime this means that dependencies in jar not installed for that you have to add all dependecies in parent project.

ankit
  • 1,919
  • 19
  • 39
-1

Goto File -> Project Structure -> Modules -> app -> Dependencies Tab -> Click on +(button) -> Select File Dependency - > Select jar file in the lib folder

This steps will automatically add your dependency to gralde

Very Simple

Jaya
  • 931
  • 10
  • 7
  • 3
    Is that a path through some Java IDE menus? Probably Idea? – Utgarda Jun 17 '16 at 10:38
  • 1
    Yes, that looks like something for IntelliJ IDEA, and I don't think it will work. Or, it will look like it is working until a change is made to the Gradle setup that results in a "synchronization" being done, and the synchronization is one-way from Gradle to the IntelliJ settings. It doesn't synchronize the other way - at least I don't think so. – RenniePet Aug 30 '16 at 00:56
  • 1
    If you have automatic import selected, the manually imported .JAR will be removed on the next change to `build.gradle`. – Jonathan Landrum Feb 11 '19 at 20:10
-1

Be careful if you are using continuous integration, you must add your libraries in the same path on your build server.

For this reason, I'd rather add jar to the local repository and, of course, do the same on the build server.

Akostha
  • 484
  • 5
  • 7
-3

An other way:

Add library in the tree view. Right click on this one. Select menu "Add As Library". A dialog appear, let you select module. OK and it's done.

emmanuel
  • 9,385
  • 10
  • 21
  • 37