2013-07-19 13 views
5

依存する2つの.dllファイルを持つ.jarがあります。実行時にこれらのファイルを.jarからユーザーの一時フォルダーにコピーする方法があるかどうかを知りたい。現在実行中のjarのファイルをコピーする方法

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; 
     } 

私の主な問題は、実行時に瓶の外に.dllファイルを取得している:ここで私は(質問のサイズを小さくするために一つだけの.dll負荷に編集した)している現在のコードです。 .jar内からパスを取得する方法は参考になります。

ありがとうございます。

+0

arround .dllファイルのパスを取得しますか? – user217895

+0

はい、ファイルにアクセスしてコピーできます。私が必要とするのはクラスパスだけです。私はすでにファイルをコピーする方法を知っています。コード例の場合、 – DeanMWake

答えて

8

dllはjarファイル内にバンドルされているので、ClassLoader#getResourceAsStreamを使用してリソースとしてacassして、ハードドライブ上のバイナリファイルとして書き込むことができます。ここで

は、いくつかのサンプルコードです:

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); 
    } 
} 

上記のコードは、現在の作業ディレクトリにパッケージsome.pack.ageにあるDLLを抽出します。

+0

+1。ありがとう。それは今少し微調整で完全に動作します。 – DeanMWake

+0

@MethodManようこそ! – A4L

+0

私はあなただと思う:あなたは*;) – DeanMWake

0

myClass.getClassLoader().getResourceAsStream("loadAtRuntime.dll");を使用すると、JARでDLLを見つけてコピーすることができます。同じJARにも含まれるクラスを選択する必要があります。

0

このJARファイル内のリソースを見つけることができるクラスローダーを使用します。 Peter Lawreyが提案したクラスのクラスローダーを使用するか、そのJARへのURLを使用してURLClassLoaderを作成することもできます。

このクラスローダーを取得したら、ClassLoader.getResourceAsStreamでバイト入力ストリームを取得できます。一方、作成するファイルに対してはFileOutputStreamを作成するだけです。

最後に、コード例ですでに行ったように、すべてのバイトを入力ストリームから出力ストリームにコピーします。

関連する問題