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

其他回答

你可以添加jar做:

对于gradle,只需在build.gradle中放入以下代码:

dependencies {
...
compile fileTree(dir: 'lib', includes: ['suitetalk-*0.jar'])
...
}

对于maven,只需遵循以下步骤:

Intellij: 文件->项目结构->模块->依赖选项卡->点击+号-> jar和依赖->选择jar你想导入->ok ->应用(如果可见)->ok

记住,如果你在运行时得到任何java.lang.NoClassDefFoundError: Could not initialize class exception,这意味着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版本)。

您还可以这样做,这将包括本地存储库中的所有jar。这样就不必每次都指定它。

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

为那些使用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")
}

一个简单的方法是

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

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