Monday, October 16, 2006

BLOG: Extract a resource from Jar file

Sometime we want to ship our product in one jar file. This is a practical solution where we can extract out the resource into a temporary file. In my specific project, I need to extract a dll out of the jar file and run the JNI call against with it.

public void extractFile(ClassLoader classLoader, String resName, File targetFile) throws IOException {

FileOutputStream fos = new FileOutputStream(targetFile);

URL url = classLoader.getResource(resName);

if (url == null) {

throw new IOException();

}

InputStream is = url.openStream();

byte[] c = new byte[BUF_LEN];

int i = 1;

while (i != -1) {

i = is.read(c, 0, BUF_LEN);

if (i > 0) {

fos.write(c, 0, i);

}

}

fos.flush();

fos.close();

}

Tony

No comments:

Thumbs Up to GitHub Copilot and JetBrains Resharper

Having used AI tool GitHub Copilot since 08/16/2023, I’ve realized that learning GitHub Copilot is like learning a new framework or library ...