Timtower

JarUtils

Feb 4th, 2015
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.90 KB | None | 0 0
  1. public class JarUtils {
  2.     public static boolean extractFromJar(final String fileName, final String dest, final JarFile jar) throws IOException {
  3.         final File file = new File(dest);
  4.         if (file.isDirectory()) {
  5.             file.mkdir();
  6.             return false;
  7.         }
  8.         if (!file.exists()) {
  9.             file.getParentFile().mkdirs();
  10.         }
  11.         final Enumeration<JarEntry> e = jar.entries();
  12.         while (e.hasMoreElements()) {
  13.             final JarEntry je = e.nextElement();
  14.             //System.out.println(je.getName());
  15.             if (!je.getName().contains(fileName)) {
  16.                 continue;
  17.             }
  18.             final InputStream in = new BufferedInputStream(jar.getInputStream(je));
  19.             final OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
  20.             copyInputStream(in, out);
  21.             jar.close();
  22.             return true;
  23.         }
  24.         jar.close();
  25.         return false;
  26.     }
  27.  
  28.     private final static void copyInputStream(final InputStream in, final OutputStream out) throws IOException {
  29.         try {
  30.             final byte[] buff = new byte[4096];
  31.             int n;
  32.             while ((n = in.read(buff)) > 0) {
  33.                 out.write(buff, 0, n);
  34.             }
  35.         } finally {
  36.             out.flush();
  37.             out.close();
  38.             in.close();
  39.         }
  40.     }
  41.  
  42.     public static void addClassPath(final File file) throws IOException{
  43.         addClassPath(getJarUrl(file));
  44.     }
  45.    
  46.     public static void addClassPath(final URL url) throws IOException {
  47.         final URLClassLoader sysloader = (URLClassLoader) ClassLoader.getSystemClassLoader();
  48.         final Class<URLClassLoader> sysclass = URLClassLoader.class;
  49.         try {
  50.             final Method method = sysclass.getDeclaredMethod("addURL", new Class[] { URL.class });
  51.             method.setAccessible(true);
  52.             method.invoke(sysloader, new Object[] { url });
  53.         } catch (final Throwable t) {
  54.             t.printStackTrace();
  55.             throw new IOException("Error adding " + url + " to system classloader");
  56.         }
  57.     }
  58.  
  59.     public static URL getJarUrl(final File file) throws IOException {
  60.         return new URL("jar:" + file.toURI().toURL().toExternalForm() + "!/");
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment