我尝试将本地.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


当前回答

我无法在https://stackoverflow.com/a/20956456/1019307上得到上面的建议。不过这对我来说很管用。对于我存储在项目根目录libs/目录中的secondstring-20030401.jar文件:

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'

其他回答

这个问题已经被详细地回答了。我还想补充一些让我很惊讶的事情:

“gradle dependencies”任务没有列出任何文件依赖项。即使你可能会这么想,因为它们已经在“依赖项”块中指定了。

因此,不要依赖于它的输出来检查所引用的本地库文件是否正常工作。

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

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

公认的答案是好的,但是,我需要在我的多项目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版本)。

对于Gradle 7.4版本,使用Groovy构建文件

repositories {
    flatDir {
        dirs 'libs'
    }
}

dependencies {
    implementation ':gson-2.2.4'
}

使用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")
    )
)

上面的代码假设库文件位于模块的libs/目录中(这里的模块指的是build.gradle.kts所在的目录)。

如上所示,可以在include和exclude中使用Ant模式。

有关文件依赖关系的更多信息,请参阅Gradle文档。

感谢这篇文章提供了一个有用的答案。