Oneiros Oneiros - 2 months ago 34
Java Question

Extract and load DLL from JAR

My Java application uses a DLL library. How can I get it work from the JAR file?

The DLL is in the project's sources folder. I have to include it in my JAR, extract it at runtime (in the same directory of the jar) and load it.

Answer

You need to put dll in your library path (recommended ) before you try to load it. so that you will have to extract it from jar and copy it into lib path .

private static void loadLib(String path, String name) {
  name = System.mapLibraryName(name); // extends name with .dll, .so or .dylib
  try {
        InputStream in = ACWrapper.class.getResourceAsStream("/"+path + name);
        File fileOut = new File("your lib path");
        OutputStream out = FileUtils.openOutputStream(fileOut);
        IOUtils.copy(in, out);
        in.close();
        out.close();
        System.load(fileOut.toString());//loading goes here
   } catch (Exception e) {
               //handle
   }
}

Note: ACWrapper is the class holding the static method