简体   繁体   English

Java 加载本机库

[英]Java Loading Native Libraries

I have printer driver on path: /home/daniel/configuration/devices/printer/CITIZENS2000/libCSJjposCom.so我在路径上有打印机驱动程序: /home/daniel/configuration/devices/printer/CITIZENS2000/libCSJjposCom.so

I need to load this driver into my java application, I'm using this code below:我需要将此驱动程序加载到我的 java 应用程序中,我正在使用以下代码:

@Override
public void addLibraryPath(String pathToAdd) {
    try {
        System.setProperty("java.library.path", System.getProperty("java.library.path") + ":/home/daniel/configuration/devices/printer/CITIZENS2000");

        System.loadLibrary("CSJjposCom");
    } catch (Exception e) {
        throw new IllegalStateException("Failed to load library", e);
    }
}


But i'm getting exception on loadLibrary() method: Method threw 'java.lang.UnsatisfiedLinkError' exception.但是我在loadLibrary() method: Method threw 'java.lang.UnsatisfiedLinkError'异常。 (no CSJjposCom in java.library.path); (java.library.path 中没有 CSJjposCom);

How can I fix it?我该如何解决?

Although you are allowed to set java.library.path in code, it won't have any effect.尽管您可以在代码中设置java.library.path ,但它不会产生任何影响。 From the documentation of System.getProperties() :System.getProperties() 的文档中

Changing a standard system property may have unpredictable results unless otherwise specified.除非另有说明,否则更改标准系统属性可能会产生不可预知的结果。 Property values may be cached during initialization or on first use.属性值可能在初始化期间或首次使用时被缓存。 Setting a standard property after initialization using getProperties() , setProperties(Properties) , setProperty(String, String) , or clearProperty(String) may not have the desired effect.使用getProperties()setProperties(Properties)setProperty(String, String)clearProperty(String)初始化后设置标准属性可能不会达到预期效果。

(Emphasis theirs.) (强调他们的。)

You have two options:你有两个选择:

  1. Set java.library.path when Java starts up: java -Djava.library.path=/home/daniel/configuration/devices/printer/CITIZENS2000 -jar MyApplication.jar Java启动时设置java.library.pathjava -Djava.library.path=/home/daniel/configuration/devices/printer/CITIZENS2000 -jar MyApplication.jar
  2. Forget about the library path, and load the driver file directly using System.load(filename) instead of Sytem.loadLibrary: System.load("/home/daniel/configuration/devices/printer/CITIZENS2000/libCSJjposCom.so")忘记库路径,直接使用System.load(filename)而不是 Sytem.loadLibrary 加载驱动程序文件: System.load("/home/daniel/configuration/devices/printer/CITIZENS2000/libCSJjposCom.so")

Obviously, the first option is only available if you have the power to specify JVM options.显然,第一个选项只有在您有权指定 JVM 选项时才可用。 And the second option will only work on the one computer where that file resides.第二个选项仅适用于该文件所在的一台计算机。

If you desire portability, you may able to bundle the library with your application, then copy it to the temporary directory and load it from there.如果您需要可移植性,您可以将库与您的应用程序捆绑在一起,然后将其复制到临时目录并从那里加载它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM