我尝试将本地.jar文件依赖项添加到构建中。gradle文件:

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

您可以看到,我将.jar文件添加到这里的referencedLibraries文件夹:https://github.com/WalnutiQ/wAlnut/tree/version-2.3.1/referencedLibraries

但问题是,当我在命令行上运行命令:gradle build时,我得到以下错误:

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

这是我的全部回购:https://github.com/WalnutiQ/wAlnut/tree/version-2.3.1


当前回答

一个简单的方法是

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

它会编译App中libs目录下的所有。jar文件。

其他回答

以下是我的工作:

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

参考Gradle文档。

公认的答案是好的,但是,我需要在我的多项目Gradle构建中进行各种库配置才能使用相同的第三方Java库。

添加“rootProject美元。projectDir'到'dir'路径元素在我的'allprojects'闭包意味着每个子项目引用相同的'libs'目录,而不是该子项目的本地版本:

//gradle.build snippet
allprojects {
    ...

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

    ...
}

编辑由Quizzie:更改“${rootProject。到$rootProject。projectDir”(适用于最新的Gradle版本)。

对我来说有效的解决方案是在构建中使用fileTree。gradle文件。 将需要添加为依赖项的.jar保存在libs文件夹中。在build.gradle的依赖块中给出以下代码:

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

一个简单的方法是

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

它会编译App中libs目录下的所有。jar文件。

您可以尝试为Gradle重用您的本地Maven存储库:

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