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:17

The accepted answer is good, however, I would have needed various library configurations within my multi-project Gradle build to use the same 3rd-party Java library.

Adding '$rootProject.projectDir' to the 'dir' path element within my 'allprojects' closure meant each sub-project referenced the same 'libs' directory, and not a version local to that sub-project:

//gradle.build snippet
allprojects {
    ...

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

    ...
}

EDIT by Quizzie: changed "${rootProject.projectDir}" to "$rootProject.projectDir" (works in the newest Gradle version).

查看更多
路过你的时光
3楼-- · 2018-12-31 09:19

You could also do this which would include all JARs in the local repository. This way you wouldn't have to specify it every time.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}
查看更多
栀子花@的思念
4楼-- · 2018-12-31 09:20

The best way to do it is to add this in your build.gradle file and hit the sync option

dependency{
    compile files('path.jar')
}
查看更多
弹指情弦暗扣
5楼-- · 2018-12-31 09:20

The Question already has been answered in detail. I still want to add something that seems very surprising for me:

The "gradle dependencies" task does not list any file dependencies. Even though you might think so, as they have been specified in the "dependencies" block after all..

So don't rely on the output of this to check whether your referenced local lib files are working correctly.

查看更多
十年一品温如言
6楼-- · 2018-12-31 09:23

An other way:

Add library in the tree view. Right click on this one. Select menu "Add As Library". A dialog appear, let you select module. OK and it's done.

查看更多
几人难应
7楼-- · 2018-12-31 09:24

Be careful if you are using continuous integration, you must add your libraries in the same path on your build server.

For this reason, I'd rather add jar to the local repository and, of course, do the same on the build server.

查看更多
登录 后发表回答