MethodMan MethodMan - 7 months ago 10
Java Question

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("");
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 = > 0) {
fileOutStream.write(bufferJNI, 0, lengthFileIn);

//close all steams
} catch (IOException e) {
return false;
} catch (UnsupportedEncodingException 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.


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

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

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