Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 572
Oneiros Avatar asked Jan 21 '11 22:01

Oneiros


1 Answers

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 void loadLib(String path, String name) {
  name = System.mapLibraryName(name); // extends name with .dll, .so or .dylib
  InputStream inputStream = null;
  OutputStream outputStream = null;
  try {
    inputStream = getClass().getResourceAsStream("/" + path + name);
    File fileOut = new File("your lib path");
    outputStream = new FileOutputStream(fileOut);
    IOUtils.copy(inputStream, outputStream);

    System.load(fileOut.toString());//loading goes here
  } catch (Exception e) {
    //handle
  } finally {
    if (inputStream != null) {
      try {
        inputStream.close();
      } catch (IOException e) {
        //log
      }
    }
    if (outputStream != null) {
      try {
        outputStream.close();
      } catch (IOException e) {
        //log
      }
    }
  }

}

Note: ACWrapper is the class holding the static method

like image 150
jmj Avatar answered Oct 23 '22 07:10

jmj