How to add local .jar file dependency to build.gra

2018-12-31 08:39发布

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

14条回答
忆尘夕之涩
2楼-- · 2018-12-31 09:03

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 {
   compile name: 'gson-2.2.4'
}

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

repositories {
   mavenCentral()
}
dependencies {
   compile 'com.google.code.gson:gson:2.2.4'
}
查看更多
公子世无双
3楼-- · 2018-12-31 09:04

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.

查看更多
查无此人
4楼-- · 2018-12-31 09:05

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'])
}
查看更多
情到深处是孤独
5楼-- · 2018-12-31 09:08

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

dependencies {
    compile files('libs/something_local.jar')
}
查看更多
低头抚发
6楼-- · 2018-12-31 09:09

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

查看更多
明月照影归
7楼-- · 2018-12-31 09:11

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 {  
      compile ("com.company:utility:0.0.1")  
    }
    
    • Now you should have the jar enabled for compilation in your project
查看更多
登录 后发表回答