如何在JAR中捆绑本机库和JNI库?

时间:2010-05-30 03:22:06

标签: java jar clojure java-native-interface tokyo-cabinet

有问题的图书馆是Tokyo Cabinet

我想在一个JAR文件中包含本机库,JNI库和所有Java API类,以避免重新分发问题。

似乎有an attempt at this at GitHub,但

  1. 它不包括实际的本机库,只包含JNI库。
  2. 它似乎特定于Leiningen的本机依赖项插件(它不能用作可再发行组件)。
  3. 问题是,我可以将所有内容捆绑在一个JAR中并重新分发吗?如果是,怎么样?

    P.S。:是的,我意识到它可能会带来便携性。

6 个答案:

答案 0 :(得分:36)

https://www.adamheinrich.com/blog/2012/12/how-to-load-native-jni-library-from-jar/

是一篇很棒的文章,它解决了我的问题..

在我的情况下,我有以下代码来初始化库:

static {
    try {
        System.loadLibrary("crypt"); // used for tests. This library in classpath only
    } catch (UnsatisfiedLinkError e) {
        try {
            NativeUtils.loadLibraryFromJar("/natives/crypt.dll"); // during runtime. .DLL within .JAR
        } catch (IOException e1) {
            throw new RuntimeException(e1);
        }
    }
}

答案 1 :(得分:16)

看看One-JAR。它将你的应用程序包装在一个jar文件中,该文件包含一个专门的类加载器,它可以处理“罐子里的罐子”等。

handles native (JNI) libraries,根据需要将它们解压缩到临时工作文件夹。

(免责声明:我从来没有使用过One-JAR,还没有使用它,只是为了下雨天给它添加了书签。)

答案 2 :(得分:5)

JarClassLoader是一个类加载器,用于从单个怪物JAR和怪物JAR内的JAR加载类,本机库和资源。

答案 3 :(得分:2)

1)将本机库作为资源包含在JAR中。 E. g。使用Maven或Gradle以及标准项目布局,将本机库放入main/resources目录。

2)在与此库相关的Java类的静态初始化器中的某处,放置如下代码:

String libName = "myNativeLib.so"; // The name of the file in resources/ dir
URL url = MyClass.class.getResource("/" + libName);
File tmpDir = Files.createTempDirectory("my-native-lib").toFile();
tmpDir.deleteOnExit();
File nativeLibTmpFile = new File(tmpDir, libName);
nativeLibTmpFile.deleteOnExit();
try (InputStream in = url.openStream()) {
    Files.copy(in, nativeLibTmpFile.toPath());
}
System.load(nativeLibTmpFile.getAbsolutePath());

答案 4 :(得分:1)

您可能必须将本机库解开到本地文件系统。据我所知,本机加载的一些代码会查看文件系统。

这段代码应该有助于你入门(我暂时没有看过它,这是为了一个不同的目的,但应该做的伎俩,我现在很忙,但如果你有问题只是发表评论,我会尽快回答。

import java.io.Closeable;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;


public class FileUtils
{
    public static String getFileName(final Class<?>  owner,
                                     final String    name)
        throws URISyntaxException,
               ZipException,
               IOException
    {
        String    fileName;
        final URI uri;

        try
        {
            final String external;
            final String decoded;
            final int    pos;

            uri      = getResourceAsURI(owner.getPackage().getName().replaceAll("\\.", "/") + "/" + name, owner);
            external = uri.toURL().toExternalForm();
            decoded  = external; // URLDecoder.decode(external, "UTF-8");
            pos      = decoded.indexOf(":/");
            fileName = decoded.substring(pos + 1);
        }
        catch(final FileNotFoundException ex)
        {
            fileName = null;
        }

        if(fileName == null || !(new File(fileName).exists()))
        {
            fileName = getFileNameX(owner, name);
        }

        return (fileName);
    }

    private static String getFileNameX(final Class<?> clazz, final String name)
        throws UnsupportedEncodingException
    {
        final URL    url;
        final String fileName;

        url = clazz.getResource(name);

        if(url == null)
        {
            fileName = name;
        }
        else
        {
            final String decoded;
            final int    pos;

            decoded  = URLDecoder.decode(url.toExternalForm(), "UTF-8");
            pos      = decoded.indexOf(":/");
            fileName = decoded.substring(pos + 1);
        }

        return (fileName);
    }

    private static URI getResourceAsURI(final String    resourceName,
                                       final Class<?> clazz)
        throws URISyntaxException,
               ZipException,
               IOException
    {
        final URI uri;
        final URI resourceURI;

        uri         = getJarURI(clazz);
        resourceURI = getFile(uri, resourceName);

        return (resourceURI);
    }

    private static URI getJarURI(final Class<?> clazz)
        throws URISyntaxException
    {
        final ProtectionDomain domain;
        final CodeSource       source;
        final URL              url;
        final URI              uri;

        domain = clazz.getProtectionDomain();
        source = domain.getCodeSource();
        url    = source.getLocation();
        uri    = url.toURI();

        return (uri);
    }

    private static URI getFile(final URI    where,
                               final String fileName)
        throws ZipException,
               IOException
    {
        final File location;
        final URI  fileURI;

        location = new File(where);

        // not in a JAR, just return the path on disk
        if(location.isDirectory())
        {
            fileURI = URI.create(where.toString() + fileName);
        }
        else
        {
            final ZipFile zipFile;

            zipFile = new ZipFile(location);

            try
            {
                fileURI = extract(zipFile, fileName);
            }
            finally
            {
                zipFile.close();
            }
        }

        return (fileURI);
    }

    private static URI extract(final ZipFile zipFile,
                               final String  fileName)
        throws IOException
    {
        final File         tempFile;
        final ZipEntry     entry;
        final InputStream  zipStream;
        OutputStream       fileStream;

        tempFile = File.createTempFile(fileName.replace("/", ""), Long.toString(System.currentTimeMillis()));
        tempFile.deleteOnExit();
        entry    = zipFile.getEntry(fileName);

        if(entry == null)
        {
            throw new FileNotFoundException("cannot find file: " + fileName + " in archive: " + zipFile.getName());
        }

        zipStream  = zipFile.getInputStream(entry);
        fileStream = null;

        try
        {
            final byte[] buf;
            int          i;

            fileStream = new FileOutputStream(tempFile);
            buf        = new byte[1024];
            i          = 0;

            while((i = zipStream.read(buf)) != -1)
            {
                fileStream.write(buf, 0, i);
            }
        }
        finally
        {
            close(zipStream);
            close(fileStream);
        }

        return (tempFile.toURI());
    }

    private static void close(final Closeable stream)
    {
        if(stream != null)
        {
            try
            {
                stream.close();
            }
            catch(final IOException ex)
            {
                ex.printStackTrace();
            }
        }
    }
}

答案 5 :(得分:0)

Kotlin解决方案:

  • in main-component.ts:将Kotlin运行时(kotlin-stdlib-1.4.0.jar)和本机库(librust_kotlin.dylib)复制到JAR

    main-component.ts
  • hide(menu) { return !(menu == true) // shortened form but result is the same } hide_menu() { this.isHidden = hide(this.menu); } 方法:将库复制到临时文件以使用绝对路径加载

    build.gradle.dsl