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


当前回答

您可以尝试为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

其他回答

为那些使用Kotlin DSL的人提供的解决方案

到目前为止添加的解决方案非常适合OP,但是如果不先翻译它们,就不能用于Kotlin DSL。下面是我如何使用Kotlin DSL向我的构建添加本地.JAR的示例:

dependencies {
    compile(files("/path/to/file.jar"))
    testCompile(files("/path/to/file.jar"))
    testCompile("junit", "junit", "4.12")
}

记住,如果你使用的是Windows,你的反斜杠必须转义:

...
compile(files("C:\\path\\to\\file.jar"))
...

还要记住,引号必须是双引号,而不是单引号。


2020年编辑:

Gradle更新已经弃用了compile和testCompile,取而代之的是implementation和testImplementation。所以上面的依赖块对于当前的Gradle版本是这样的:

dependencies {
    implementation(files("/path/to/file.jar"))
    testImplementation(files("/path/to/file.jar"))
    testImplementation("junit", "junit", "4.12")
}

如果您正在使用持续集成,请小心,您必须将库添加到构建服务器上的相同路径中。

出于这个原因,我宁愿将jar添加到本地存储库,当然,在构建服务器上也做同样的事情。

最好的方法是在构建中添加这个功能。Gradle文件,然后点击同步选项

dependency{
    compile files('path.jar')
}

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

repositories {
    flatDir {
        dirs 'libs'
    }
}

dependencies {
    implementation ':gson-2.2.4'
}

如果你真的需要从本地目录中获取。jar文件,

添加到你的模块gradle(不是应用程序的gradle文件):

repositories {
   flatDir {
       dirs("libs")
   }
}


dependencies {
   implementation("gson-2.2.4")
}

但是,作为实际maven存储库中的标准.jar,为什么不尝试一下呢?

repositories {
   mavenCentral()
}
dependencies {
   implementation("com.google.code.gson:gson:2.2.4")
}