Search code examples
javadrivernativelibrariesthermal-printer

Java Loading Native Libraries


I have printer driver on path: /home/daniel/configuration/devices/printer/CITIZENS2000/libCSJjposCom.so

I need to load this driver into my java application, I'm using this code below:

@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. (no CSJjposCom in java.library.path);

How can I fix it?


Solution

  • Although you are allowed to set java.library.path in code, it won’t have any effect. From the documentation of 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.

    (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
    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")

    Obviously, the first option is only available if you have the power to specify JVM options. 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.