How to add local .jar file dependency to build.gradle file?
Asked Answered
A

22

819

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

Avaavadavat answered 20/12, 2013 at 9:14 Comment(4)
Are you sure about runtime instead of compile? compile files (....)Surbeck
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.Precancel
This Stack Overflow question finally gave me the answer I needed.Carpic
Does this answer your question? Android Studio: Add jar as library?Introspection
S
561

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("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")
}
Scenic answered 20/12, 2013 at 9:21 Comment(10)
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)Chitin
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'}Orgeat
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 ;-)Carnarvon
I am having a gradle.build file - What is these "app gradle file" and the "module gradle"?Hynes
What if my jar is based in Gradle, not Maven?Core
Any chance someone will update the answer with a link to the official Gradle documentation section describing these features?Crutcher
How to apply this using Kotlin DSL? compile name: 'gson-2.2.4'Kamerad
implementation(":gson:2.2.4") seems to be the way to do it.Kamerad
Instead of implementation name:'local-lib-4.1.2-876' I could also use implementation name: 'local-lib', version: '4.1.2-876'Unknot
Doesn't work with Spring Boot plugin bootJar task. Solution below did work https://mcmap.net/q/48137/-how-to-add-local-jar-file-dependency-to-build-gradle-fileBeige
S
983

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

Groovy syntax:

dependencies {
    implementation files('libs/something_local.jar')
}

Kotlin syntax:

dependencies {
    implementation(files("libs/something_local.jar"))
}
Shrovetide answered 6/1, 2014 at 18:12 Comment(9)
@Gubatron it's documented now: gradle.org/docs/current/userguide/…Milano
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.Epilogue
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.Congelation
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://mcmap.net/q/48696/-how-to-make-gradle-fail-the-build-if-a-file-dependency-is-not-found/4851565Chartres
i was getting a similar error even after using this solution. Mistake i did put libs folder under apps not in same level as appsCalamander
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.Acoustician
can some one help both defining flatDir. and adding just the dependency as implementation fileTree do not add the local libs/jar file @gradle 6.5Biogenesis
What is the equivalent of this so that it would work in Kubernetes as well.Cadastre
It's worth mentioning that the libs/ directory in the example is based at the root of the git repo.Jews
S
561

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("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")
}
Scenic answered 20/12, 2013 at 9:21 Comment(10)
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)Chitin
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'}Orgeat
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 ;-)Carnarvon
I am having a gradle.build file - What is these "app gradle file" and the "module gradle"?Hynes
What if my jar is based in Gradle, not Maven?Core
Any chance someone will update the answer with a link to the official Gradle documentation section describing these features?Crutcher
How to apply this using Kotlin DSL? compile name: 'gson-2.2.4'Kamerad
implementation(":gson:2.2.4") seems to be the way to do it.Kamerad
Instead of implementation name:'local-lib-4.1.2-876' I could also use implementation name: 'local-lib', version: '4.1.2-876'Unknot
Doesn't work with Spring Boot plugin bootJar task. Solution below did work https://mcmap.net/q/48137/-how-to-add-local-jar-file-dependency-to-build-gradle-fileBeige
R
365

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'])
}
Roussel answered 27/5, 2014 at 19:43 Comment(7)
This is used for compiling all the jars in lib directory. Its the perfect solution (y)Seligmann
...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.Cantor
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.Escrow
Note that dir can be an absolute path as well. Also instead of 'include' I had to use 'includes'.Haehaecceity
for gradle 7+ go with implementation fileTree(dir: 'lib', includes: ['*.jar']) (or api, depending on your needs)Anorak
can some one help both defining flatDir. and adding just the dependency as implementation fileTree do not add the local libs/jar file @gradle 6.5Biogenesis
@Cantor I am working on the same task you explained in the comment. Can we discuss more?Titrant
K
61

The following works for me:

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

Refer to the Gradle Documentation.

Kiblah answered 5/8, 2017 at 17:5 Comment(6)
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 libraryPayton
How is this different than @Nightwolf's answer?Samale
Could not find method compile() for arguments [directory 'libs'] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandlerKerenkeresan
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.aarPromisee
The new version of the Gradle does not support "compile" and we need to use "implementation" instead. so something like "implementation fileTree(dir: 'libs', include: ['*.jar'])"Furan
this is a simple fileTree spec so, everything that applies to fileTree spec applies to this too, hence you can exclude any specific item using compile fileTree(dir: 'libs', include: '*.jar', exclude: 'junit.jar') something like that.Censer
C
50

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
Cataclysmic answered 23/12, 2016 at 1:40 Comment(4)
This one helped me when all else failed!Blue
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.Telepathy
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.Bighead
Worked for me after putting values in double quotes ` mvn install:install-file -Dfile="utils-1.0.5.jar" -DgroupId="com.company" -DartifactId=commons -Dversion="3.1.3" -Dpackaging=jar `Belindabelisarius
M
38

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")
}
Missionary answered 11/2, 2019 at 20:8 Comment(2)
+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)?Cyb
@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").Missionary
J
36

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).

Josselyn answered 10/12, 2014 at 16:28 Comment(6)
but how to refer this libs folder in library build.gradle file? Any help on that.Meat
Just change "${rootProject.projectDir}" to "$rootProject.projectDir" to make it work again.Machinate
Be sure to use double quotes rather than single quotes as the latter will not be interpolated.Datura
This approach helped me.Le
All of the answers here helped me a lot. This pattern is one we are using and it makes it easy for people working in teams to just drop JARs into that directory when working on branches.Behold
Simpler to use rootDirDoukhobor
O
20

Shorter version:

dependencies {
    implementation fileTree('lib')
}
Overthecounter answered 22/6, 2020 at 18:6 Comment(0)
M
16

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.

Marsha answered 30/10, 2015 at 16:7 Comment(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.Perseverance
C
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.

Cagey answered 18/8, 2015 at 9:10 Comment(6)
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?Chaffin
No, it doesn't. Technically it shouldn't as well, as we are giving the 'dir:libs' not subdirectories of libs.Cagey
In this case how to get all the libraries from the subdirectories with minimum tasks (because our project contains so many subdirectories.Chaffin
Hey @mallikgm sorry for late reply, did you tried adding wildcard in dir path like compile fileTree(include: ['.jar'], dir: 'libs')Cagey
How is this different than @Nightwolf's answer?Samale
I think this is the best solution. This is already in your build.gradle if you generated it using intellij "android" new project typeChopin
I
10

Some more ways to add local library files using Kotlin DSL (build.gradle.kts):

implementation(
    files(
        "libs/library-1.jar",
        "libs/library-2.jar",
        "$rootDir/foo/my-other-library.jar"
    )
)
implementation(
    fileTree("libs/") {
        // You can add as many include or exclude calls as you want
        include("*.jar")
        include("another-library.aar") // Some Android libraries are in AAR format
        exclude("bad-library.jar")
    }
)
implementation(
    fileTree(
        "dir" to "libs/",
        // Here, instead of repeating include or exclude, assign a list of paths
        "include" to "*.jar",
        "exclude" to listOf("bad-library-1.jar", "bad-library-2.jar")
    )
)

The above code assumes that the library files are in libs/ directory of the module (by module I mean the directory where this build.gradle.kts is located).

You can use Ant patterns in includes and excludes as shown above.

See Gradle documentations for more information about file dependencies.

Thanks to this post for providing a helpful answer.

Introspection answered 25/1, 2022 at 14:5 Comment(0)
I
8

I couldn't get the suggestion above at https://mcmap.net/q/48137/-how-to-add-local-jar-file-dependency-to-build-gradle-file 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'
Indecipherable answered 18/3, 2015 at 6:40 Comment(3)
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.Chiasma
Nah, this doesn't work me Could not find :miglayout-core:. Searched in the following locations: file:/user/path/to/miglayout-core.jarGranivorous
this work if you want add a file directory as repository : docs.gradle.org/current/userguide/…Aideaidedecamp
C
7

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')
}
Choline answered 12/8, 2016 at 8:4 Comment(0)
F
7

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'])
}
Fulks answered 24/8, 2016 at 5:21 Comment(0)
T
4

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.

Thrombophlebitis answered 5/7, 2019 at 10:57 Comment(0)
L
4

If you are on gradle 4.10 or newer:

implementation fileTree(dir: 'libs', includes: ['*.jar'])
Laryngo answered 1/4, 2022 at 13:50 Comment(0)
G
3

For Gradle version 7.4 with Groovy build file

repositories {
    flatDir {
        dirs 'libs'
    }
}

dependencies {
    implementation ':gson-2.2.4'
}
Grubstake answered 5/3, 2022 at 12:50 Comment(0)
R
0

Add below line inside the "dependencies definition" of your build.gradle file:

implementation files("/Users/<user_name>/<folder_structure>/<jar_name>.jar")

This worked for me to take .jar file from my local system for the specific project.

Retribution answered 24/7, 2023 at 19:5 Comment(0)
D
0

This is working in Gradle 8.3. If you are doing it on Windows then refer below

repositories {
flatDir { dirs 'D:/path/of/jar/lib' } } dependencies { implementation ':json-resource2.4.0' }

Dingo answered 21/9, 2023 at 14:25 Comment(0)
F
-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.

Fidge answered 17/10, 2017 at 11:17 Comment(0)
C
-2

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

Congenial answered 17/3, 2016 at 7:19 Comment(3)
Is that a path through some Java IDE menus? Probably Idea?Windhoek
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.Michaelis
If you have automatic import selected, the manually imported .JAR will be removed on the next change to build.gradle.Missionary
R
-4

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.

Rabblerouser answered 16/12, 2014 at 11:10 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.