how I can load a library 开发者_如何学JAVAfrom a jar? e.g.
Test.jar
+- libAbc.so
+- libDef.so
+- ...
Probably not the answer you are looking for (extracting the file to a temp location is the answer you are looking for), but I thought I'd share some real world experience:
The plumbing required to exctract the library from jar, make sure it gets cleaned up afterwards, doesn't conflict with other applications that might be using the jar, etc... is very tricky. It can be done, but chances are very good that you'll wind up with either tons of temp copies of your libraries cluttering the user's system, or you'll wind up with conflicts between multiple apps using the libraries.
When you add the fact that many operating systems don't allow just any file to be used as a library (and frequently, the permissions for the user who will be running your app do not allow them to mark an arbitrary file in the temp folder for execution), the idea of packaging the native libraries inside the jar becomes less attractive.
What we finally wound up doing was shifting to a model where we have our installer (which does run with sufficient permissions) place the appropriate native library alongside the jar. This is fairly simple to do, keeps all executing libraries in the same place, and is easy to administer and understand (trying to track down a version incompatibility in one application b/c it is trying to load a library that was saved to temp storage by a second application is a total nightmare).
Native code is being loaded by the underlying operating system, and if that code cannot peek inside a jar-file to pick up the bytes you want to load - which Windows cannot - you must make it accessible in the file system yourself.
Can you deploy your library next to your jar file?
You have to unpack it into some temporary dir and the use `System.load("path/to/libAbc.so").
This has been discussed previously.
Edited: corrected the link.
Libraries must be loaded from the filesystem. So you could extract your library from the jar into a temp directory and load it.
You would have to extract the files from the JAR and load them with;
System.load("path/to/files/<name>.so");
But don't forget to perhaps clean up the files after the program has shut down, if it doesn't take too long to extract them;
libraryFile.deleteOnExit();
精彩评论