View Javadoc
1   package com.simpligility.maven.plugins.androidndk.common;
2   
3   import org.apache.commons.io.IOUtils;
4   import org.codehaus.plexus.util.IOUtil;
5   
6   import java.io.File;
7   import java.io.FileOutputStream;
8   import java.io.IOException;
9   import java.io.InputStream;
10  import java.io.OutputStream;
11  import java.util.Enumeration;
12  import java.util.jar.JarEntry;
13  import java.util.jar.JarFile;
14  
15  /**
16   * Helper class to deal with jar files.
17   *
18   * @author Johan Lindquist
19   */
20  public class JarHelper
21  {
22  
23      /**
24       * Listener for jar extraction.
25       */
26      public interface UnjarListener
27      {
28         boolean include( JarEntry jarEntry );
29      }
30  
31      /**
32       * Unjars the specified jar file into the the specified directory
33       *
34       * @param jarFile
35       * @param outputDirectory
36       * @param unjarListener
37       * @throws IOException
38       */
39      public static void unjar( JarFile jarFile, File outputDirectory, UnjarListener unjarListener ) throws IOException
40      {
41          for ( Enumeration en = jarFile.entries(); en.hasMoreElements(); )
42          {
43              JarEntry entry = ( JarEntry ) en.nextElement();
44              File entryFile = new File( outputDirectory, entry.getName() );
45              if ( unjarListener.include( entry ) )
46              {
47                  // Create the output directory if need be
48                  if ( ! entryFile.getParentFile().exists() )
49                  {
50                      if ( ! entryFile.getParentFile().mkdirs() )
51                      {
52                          throw new IOException( "Error creating output directory: " + entryFile.getParentFile() );
53                      }
54                  }
55  
56                  // If the entry is an actual file, unzip that too
57                  if ( ! entry.isDirectory() )
58                  {
59                      final InputStream in = jarFile.getInputStream( entry );
60                      try
61                      {
62                          final OutputStream out = new FileOutputStream( entryFile );
63                          try
64                          {
65                              IOUtil.copy( in, out );
66                          }
67                          finally
68                          {
69                              IOUtils.closeQuietly( out );
70                          }
71                      }
72                      finally
73                      {
74                          IOUtils.closeQuietly( in );
75                      }
76                  }
77              }
78          }
79      }
80  
81  }