protected ExtractedFileInformation extractFileFromArchive ( String fileName , String regex ) throws RepositoryArchiveException , RepositoryArchiveEntryNotFoundException , RepositoryArchiveIOException { JarFile jarFile = null ; ExtractedFileInformation result = null ; File outputFile = null ; File sourceArchive = new File ( fileName ) ; try { try { jarFile = new JarFile ( sourceArchive ) ; } catch ( FileNotFoundException | NoSuchFileException fne ) { throw new RepositoryArchiveException ( "Unable to locate archive " + fileName , sourceArchive , fne ) ; } catch ( IOException ioe ) { throw new RepositoryArchiveIOException ( "Error opening archive " , sourceArchive , ioe ) ; } Enumeration < JarEntry > enumEntries = jarFile . entries ( ) ; // Iterate through the files in the jar file searching for one we // are interested in while ( enumEntries . hasMoreElements ( ) ) { JarEntry entry = enumEntries . nextElement ( ) ; String name = entry . getName ( ) ; if ( Pattern . matches ( regex , name ) ) { // Don't want to use the entire path to the file so create a // file // and then recreate it using just the "name" part of the // filename outputFile = new File ( name ) ; outputFile = new File ( outputFile . getName ( ) ) ; outputFile . deleteOnExit ( ) ; try { copyStreams ( jarFile . getInputStream ( entry ) , new FileOutputStream ( outputFile ) ) ; } catch ( IOException ioe ) { throw new RepositoryArchiveIOException ( "Failed to extract file " + name + " inside " + fileName + " to " + outputFile . getAbsolutePath ( ) , sourceArchive , ioe ) ; } result = new ExtractedFileInformation ( outputFile , sourceArchive , name ) ; break ; } } } finally { try { if ( null != jarFile ) { jarFile . close ( ) ; } } catch ( IOException e ) { e . printStackTrace ( ) ; throw new RepositoryArchiveIOException ( "Error closing archive " , sourceArchive , e ) ; } } // Make sure we have found a file if ( null == outputFile ) { throw new RepositoryArchiveEntryNotFoundException ( "Failed to find file matching regular expression <" + regex + "> inside archive " + fileName , sourceArchive , regex ) ; } return result ; }
Extract a file from a jar file to a temporary location on disk that is deleted when the jvm exits .