[java] How to add local .jar file dependency to build.gradle file?

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

The answer is


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.


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.


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")
}

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.


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


The following works for me:

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

Refer to the Gradle Documentation.


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'])
}

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'

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.


Shorter version:

dependencies {
    implementation fileTree('lib')
}

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

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.


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


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'])
}

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

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

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')
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to gradle

Gradle - Move a folder from ABC to XYZ A failure occurred while executing com.android.build.gradle.internal.tasks Gradle: Could not determine java version from '11.0.2' Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0 Failed to resolve: com.android.support:appcompat-v7:28.0 Failed to resolve: com.google.firebase:firebase-core:16.0.1 com.google.android.gms:play-services-measurement-base is being requested by various other libraries java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

Examples related to dependency-management

What's the difference between implementation and compile in Gradle? How to install a specific version of package using Composer? How to clear cache in Yarn? Javascript require() function giving ReferenceError: require is not defined How to add local .jar file dependency to build.gradle file? How to clean old dependencies from maven repositories? Android Studio: Add jar as library? Dealing with "Xerces hell" in Java/Maven? How do I add a Maven dependency in Eclipse? Force re-download of release dependency using Maven

Examples related to build.gradle

Android Material and appcompat Manifest merger failed Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve Android dependency has different version for the compile and runtime Setting up Gradle for api 26 (Android) What's the difference between implementation and compile in Gradle? More than one file was found with OS independent path 'META-INF/LICENSE' Android Studio - Failed to notify project evaluation listener error Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2 All com.android.support libraries must use the exact same version specification DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

Examples related to gradle-eclipse

How to add local .jar file dependency to build.gradle file?