Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class JarUtils {
- public static boolean extractFromJar(final String fileName, final String dest, final JarFile jar) throws IOException {
- final File file = new File(dest);
- if (file.isDirectory()) {
- file.mkdir();
- return false;
- }
- if (!file.exists()) {
- file.getParentFile().mkdirs();
- }
- final Enumeration<JarEntry> e = jar.entries();
- while (e.hasMoreElements()) {
- final JarEntry je = e.nextElement();
- //System.out.println(je.getName());
- if (!je.getName().contains(fileName)) {
- continue;
- }
- final InputStream in = new BufferedInputStream(jar.getInputStream(je));
- final OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
- copyInputStream(in, out);
- jar.close();
- return true;
- }
- jar.close();
- return false;
- }
- private final static void copyInputStream(final InputStream in, final OutputStream out) throws IOException {
- try {
- final byte[] buff = new byte[4096];
- int n;
- while ((n = in.read(buff)) > 0) {
- out.write(buff, 0, n);
- }
- } finally {
- out.flush();
- out.close();
- in.close();
- }
- }
- public static void addClassPath(final File file) throws IOException{
- addClassPath(getJarUrl(file));
- }
- public static void addClassPath(final URL url) throws IOException {
- final URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
- final Class<URLClassLoader> sysclass = URLClassLoader.class;
- try {
- final Method method = sysclass.getDeclaredMethod("addURL", new Class[] { URL.class });
- method.setAccessible(true);
- method.invoke(sysloader, new Object[] { url });
- } catch (final Throwable t) {
- t.printStackTrace();
- throw new IOException("Error adding " + url + " to system classloader");
- }
- }
- public static URL getJarUrl(final File file) throws IOException {
- return new URL("jar:" + file.toURI().toURL().toExternalForm() + "!/");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment