Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...