简体   繁体   中英

How to export a runnable JAR embedding a native library in Eclipse?

I have a Java app that makes use of a native library. It works fine when I export my runnable JAR, but I have to put the native library in the same folder of the executable.

Not sure exists a procedure to do so since it's a native library, but, does exist a way to avoid putting in the same folder the library and embedding that lib inside the runnable JAR?

I use Eclipse and the successfully working procedure I used to enable the native library is the following (it maybe helpful for somebody struggling with this problem):

  1. Select the project in the Package Explorer and right-click;
  2. Build Path → Configure Build Path;
  3. Libraries tab;
  4. JRE System library option and Native library location;
  5. Edit on the right panel;
  6. Browse to the library;
  7. Close the window.

To elaborate on the answer I pointed to in the comments, it's possible to deploy a native library inside a JAR. But you have to provide for this in your code. You will have to write your code in a way that it

  • extracts the library from the jar to some temporary location (usually copying what getResourceAsStream() gives you)
  • and uses the full path name to load the library (using load() instead of loadLibrary )

Example:

Path tempPath = Paths.get("some/path");
try (InputStream inputStream = myClass.getResourceAsStream("myLibrary")) {
    Files.copy(inputStream, tempPath);
}
System.load(tempPath.toAbsolutePath().toString());

Be aware that some malware scanners prevent loading of libraries from inside the temporary directory so you will have to choose the target path carefully.

Take a look here: https://github.com/mkowsiak/jnicookbook/tree/master/recipes/recipeNo031

The idea is quite simple:

  • you have to embed native code inside JAR,
  • once code is running you have to extract the library,
  • you have to load it inside your code.

Note that libraries are usually loaded from the file system and it's not possible to load them from the buffer. This is why you have to create temporary location.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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