Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy files out of the currently running jar

I have a .jar that has two .dll files that it is dependent on. I would like to know if there is any way for me to copy these files from within the .jar to a users temp folder at runtime. here is the current code that I have (edited to just one .dll load to reduce question size):

public String tempDir = System.getProperty("java.io.tmpdir");
public String workingDir = dllInstall.class.getProtectionDomain().getCodeSource().getLocation().getPath();

public boolean installDLL() throws UnsupportedEncodingException {

try {
             String decodedPath = URLDecoder.decode(workingDir, "UTF-8");
             InputStream fileInStream = null;
             OutputStream fileOutStream = null;

             File fileIn = new File(decodedPath + "\\loadAtRuntime.dll");
             File fileOut = new File(tempDir + "loadAtRuntime.dll");

             fileInStream = new FileInputStream(fileIn);
             fileOutStream = new FileOutputStream(fileOut);

             byte[] bufferJNI = new byte[8192000013370000];
             int lengthFileIn;

             while ((lengthFileIn = fileInStream.read(bufferJNI)) > 0) {
                fileOutStream.write(bufferJNI, 0, lengthFileIn);
             }

            //close all steams
        } catch (IOException e) {
      e.printStackTrace();
             return false;
        } catch (UnsupportedEncodingException e) {
             System.out.println(e);
              return false;
        }

My main problem is getting the .dll files out of the jar at runtime. Any way to retrieve the path from within the .jar would be helpful.

Thanks in advance.

like image 376
DeanMWake Avatar asked Jul 19 '13 12:07

DeanMWake


People also ask

How do I export a JAR file with resources?

Either from the context menu or from the menu bar's File menu, select Export. Expand the Java node and select JAR file. Click Next. In the JAR File Specification page, select the resources that you want to export in the Select the resources to export field.


1 Answers

Since your dlls are bundeled inside your jar file you could just try to acasses them as resources using ClassLoader#getResourceAsStream and write them as binary files any where you want on the hard drive.

Here is some sample code:

InputStream ddlStream = <SomeClassInsideTheSameJar>.class
    .getClassLoader().getResourceAsStream("some/pack/age/somelib.dll");

try (FileOutputStream fos = new FileOutputStream("somelib.dll");){
    byte[] buf = new byte[2048];
    int r;
    while(-1 != (r = ddlStream.read(buf))) {
        fos.write(buf, 0, r);
    }
}

The code above will extract the dll located in the package some.pack.age to the current working directory.

like image 127
A4L Avatar answered Nov 01 '22 22:11

A4L