List of usage examples for java.util.zip ZipInputStream getNextEntry
public ZipEntry getNextEntry() throws IOException
From source file:com.joliciel.talismane.extensions.corpus.CorpusStatistics.java
public static CorpusStatistics loadFromFile(File inFile) { try {/*from w w w. j a v a2s . c o m*/ ZipInputStream zis = new ZipInputStream(new FileInputStream(inFile)); zis.getNextEntry(); ObjectInputStream in = new ObjectInputStream(zis); CorpusStatistics stats = null; try { stats = (CorpusStatistics) in.readObject(); } catch (ClassNotFoundException e) { LogUtils.logError(LOG, e); throw new RuntimeException(e); } return stats; } catch (IOException ioe) { LogUtils.logError(LOG, ioe); throw new RuntimeException(ioe); } }
From source file:com.twemyeez.picklr.InstallManager.java
public static void unzip() { // Firstly get the working directory String workingDirectory = Minecraft.getMinecraft().mcDataDir.getAbsolutePath(); // If it ends with a . then remove it if (workingDirectory.endsWith(".")) { workingDirectory = workingDirectory.substring(0, workingDirectory.length() - 1); }//from w w w . j a va 2 s. co m // If it doesn't end with a / then add it if (!workingDirectory.endsWith("/") && !workingDirectory.endsWith("\\")) { workingDirectory = workingDirectory + "/"; } // Use a test file to see if libraries installed File file = new File(workingDirectory + "mods/mp3spi1.9.5.jar"); // If the libraries are installed, return if (file.exists()) { System.out.println("Checking " + file.getAbsolutePath()); System.out.println("Target file exists, so not downloading API"); return; } // Now try to download the libraries try { String location = "http://www.javazoom.net/mp3spi/sources/mp3spi1.9.5.zip"; // Define the URL URL url = new URL(location); // Get the ZipInputStream ZipInputStream zipInput = new ZipInputStream(new BufferedInputStream((url).openStream())); // Use a temporary ZipEntry as a buffer ZipEntry zipFile; // While there are more file entries while ((zipFile = zipInput.getNextEntry()) != null) { // Check if it is one of the file names that we want to copy Boolean required = false; if (zipFile.getName().indexOf("mp3spi1.9.5.jar") != -1) { required = true; } if (zipFile.getName().indexOf("jl1.0.1.jar") != -1) { required = true; } if (zipFile.getName().indexOf("tritonus_share.jar") != -1) { required = true; } if (zipFile.getName().indexOf("LICENSE.txt") != -1) { required = true; } // If it is, then we shall now copy it if (!zipFile.getName().replace("MpegAudioSPI1.9.5/", "").equals("") && required) { // Get the file location String tempFile = new File(zipFile.getName()).getName(); tempFile = tempFile.replace("LICENSE.txt", "MpegAudioLicence.txt"); // Initialise the target file File targetFile = (new File( workingDirectory + "mods/" + tempFile.replace("MpegAudioSPI1.9.5/", ""))); // Print a debug/alert message System.out.println("Picklr is extracting to " + workingDirectory + "mods/" + tempFile.replace("MpegAudioSPI1.9.5/", "")); // Make parent directories if required targetFile.getParentFile().mkdirs(); // If the file does not exist, create it if (!targetFile.exists()) { targetFile.createNewFile(); } // Create a buffered output stream to the destination BufferedOutputStream destinationOutput = new BufferedOutputStream( new FileOutputStream(targetFile, false), 2048); // Store the data read int bytesRead; // Data buffer byte dataBuffer[] = new byte[2048]; // While there is still data to write while ((bytesRead = zipInput.read(dataBuffer, 0, 2048)) != -1) { // Write it to the output stream destinationOutput.write(dataBuffer, 0, bytesRead); } // Flush the output destinationOutput.flush(); // Close the output stream destinationOutput.close(); } } // Close the zip input zipInput.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:net.grinder.util.LogCompressUtil.java
/** * Uncompress the given the {@link InputStream} into the given {@link OutputStream}. * /*w w w. ja v a2s . co m*/ * @param inputStream * input stream of the compressed file * @param outputStream * file to be written * @param limit * the limit of the output */ public static void unCompress(InputStream inputStream, OutputStream outputStream, long limit) { ZipInputStream zipInputStream = null; try { zipInputStream = new ZipInputStream(inputStream); byte[] buffer = new byte[COMPRESS_BUFFER_SIZE]; int count = 0; long total = 0; checkNotNull(zipInputStream.getNextEntry(), "In zip, it should have at least one entry"); while ((count = zipInputStream.read(buffer, 0, COMPRESS_BUFFER_SIZE)) != -1) { total += count; if (total >= limit) { break; } outputStream.write(buffer, 0, count); } outputStream.flush(); } catch (IOException e) { LOGGER.error("Error occurs while uncompress"); LOGGER.error("Details", e); return; } finally { IOUtils.closeQuietly(zipInputStream); } }
From source file:com.aaasec.sigserv.cscommon.DocTypeIdentifier.java
/** * Guess the document format and return an appropriate document type string * * @param is An InputStream holding the document * @return "xml" if the document is an XML document or "pdf" if the document * is a PDF document, or else an error message. *///from w ww . ja va 2 s . com public static SigDocumentType getDocType(InputStream is) { InputStream input = null; try { input = new BufferedInputStream(is); input.mark(5); byte[] preamble = new byte[5]; int read = 0; try { read = input.read(preamble); input.reset(); } catch (IOException ex) { return SigDocumentType.Unknown; } if (read < 5) { return SigDocumentType.Unknown; } String preambleString = new String(preamble); byte[] xmlPreable = new byte[] { '<', '?', 'x', 'm', 'l' }; byte[] xmlUtf8 = new byte[] { -17, -69, -65, '<', '?' }; if (Arrays.equals(preamble, xmlPreable) || Arrays.equals(preamble, xmlUtf8)) { return SigDocumentType.XML; } else if (preambleString.equals("%PDF-")) { return SigDocumentType.PDF; } else if (preamble[0] == 'P' && preamble[1] == 'K') { ZipInputStream asics = new ZipInputStream(new BufferedInputStream(is)); ByteArrayOutputStream datafile = null; ByteArrayOutputStream signatures = null; ZipEntry entry; try { while ((entry = asics.getNextEntry()) != null) { if (entry.getName().equals("META-INF/signatures.p7s")) { signatures = new ByteArrayOutputStream(); IOUtils.copy(asics, signatures); signatures.close(); } else if (entry.getName().equalsIgnoreCase("META-INF/signatures.p7s")) { /* Wrong case */ // asics;Non ETSI compliant return SigDocumentType.Unknown; } else if (entry.getName().indexOf("/") == -1) { if (datafile == null) { datafile = new ByteArrayOutputStream(); IOUtils.copy(asics, datafile); datafile.close(); } else { // // asics;ASiC-S profile support only one data file return SigDocumentType.Unknown; } } } } catch (Exception ex) { // null;Invalid ASiC-S return SigDocumentType.Unknown; } if (datafile == null || signatures == null) { // asics;ASiC-S profile support only one data file with CAdES signature return SigDocumentType.Unknown; } // asics/cades return SigDocumentType.Unknown; } else if (preambleString.getBytes()[0] == 0x30) { // cades; return SigDocumentType.Unknown; } else { // null;Document format not recognized/handled return SigDocumentType.Unknown; } } finally { if (input != null) { try { input.close(); } catch (IOException e) { } } } }
From source file:com.ibm.jaggr.core.util.ZipUtil.java
/** * Extracts the specified zip file to the specified location. If {@code selector} is specified, * then only the entry specified by {@code selector} (if {@code selector} is a filename) or the * contents of the directory specified by {@code selector} (if {@code selector} is a directory * name) will be extracted. If {@code selector} specifies a directory, then the contents of the * directory in the zip file will be rooted at {@code destDir} when extracted. * * @param zipFile/*w w w . ja v a2 s . c om*/ * the {@link File} object for the file to unzip * @param destDir * the {@link File} object for the target directory * @param selector * The name of a file or directory to extract * @throws IOException */ public static void unzip(File zipFile, File destDir, String selector) throws IOException { final String sourceMethod = "unzip"; //$NON-NLS-1$ final boolean isTraceLogging = log.isLoggable(Level.FINER); if (isTraceLogging) { log.entering(sourceClass, sourceMethod, new Object[] { zipFile, destDir }); } boolean selectorIsFolder = selector != null && selector.charAt(selector.length() - 1) == '/'; ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zipFile)); try { ZipEntry entry = zipIn.getNextEntry(); // iterates over entries in the zip file while (entry != null) { String entryName = entry.getName(); if (selector == null || !selectorIsFolder && entryName.equals(selector) || selectorIsFolder && entryName.startsWith(selector) && entryName.length() != selector.length()) { if (selector != null) { if (selectorIsFolder) { // selector is a directory. Strip selected path entryName = entryName.substring(selector.length()); } else { // selector is a filename. Extract the filename portion of the path int idx = entryName.lastIndexOf("/"); //$NON-NLS-1$ if (idx != -1) { entryName = entryName.substring(idx + 1); } } } File file = new File(destDir, entryName.replace("/", File.separator)); //$NON-NLS-1$ if (!entry.isDirectory()) { // if the entry is a file, extract it extractFile(entry, zipIn, file); } else { // if the entry is a directory, make the directory extractDirectory(entry, file); } zipIn.closeEntry(); } entry = zipIn.getNextEntry(); } } finally { zipIn.close(); } if (isTraceLogging) { log.exiting(sourceClass, sourceMethod); } }
From source file:com.amalto.core.jobox.util.JoboxUtil.java
public static void extract(String zipPathFile, String destinationPath) throws Exception { FileInputStream fins = new FileInputStream(zipPathFile); ZipInputStream zipInputStream = new ZipInputStream(fins); try {/* www . j av a 2 s . co m*/ ZipEntry ze; byte ch[] = new byte[256]; while ((ze = zipInputStream.getNextEntry()) != null) { File zipFile = new File(destinationPath + ze.getName()); File zipFilePath = new File(zipFile.getParentFile().getPath()); if (ze.isDirectory()) { if (!zipFile.exists()) { if (!zipFile.mkdirs()) { LOGGER.error("Create folder failed for '" + zipFile.getAbsolutePath() + "'."); //$NON-NLS-1$ //$NON-NLS-2$ } } zipInputStream.closeEntry(); } else { if (!zipFilePath.exists()) { if (!zipFilePath.mkdirs()) { LOGGER.error("Create folder failed for '" + zipFilePath.getAbsolutePath() + "'."); //$NON-NLS-1$ //$NON-NLS-2$ } } FileOutputStream fileOutputStream = new FileOutputStream(zipFile); try { int i; while ((i = zipInputStream.read(ch)) != -1) { fileOutputStream.write(ch, 0, i); } zipInputStream.closeEntry(); } finally { fileOutputStream.close(); } } } } finally { IOUtils.closeQuietly(fins); IOUtils.closeQuietly(zipInputStream); } }
From source file:mashapeautoloader.MashapeAutoloader.java
/** * @param libraryName//from w w w.ja v a 2s . c o m * * Returns false if something wrong, otherwise true (API interface * already exists or just well downloaded) */ private static boolean downloadLib(String libraryName) { URL url; URLConnection urlConn; // check (or make) for apiStore directory File apiStoreDir = new File(apiStore); if (!apiStoreDir.isDirectory()) apiStoreDir.mkdir(); String javaFilePath = apiStore + libraryName + ".java"; File javaFile = new File(javaFilePath); // check if the API interface exists if (javaFile.exists()) return true; try { // download the API interface's archive url = new URL(MASHAPE_DOWNLOAD_ROOT + libraryName); urlConn = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) urlConn; httpConn.setInstanceFollowRedirects(false); urlConn.setDoInput(true); urlConn.setDoOutput(false); urlConn.setUseCaches(false); // extract the archive stream ZipInputStream zip = new ZipInputStream(urlConn.getInputStream()); String expectedEntryName = libraryName + ".java"; while (true) { ZipEntry nextEntry = zip.getNextEntry(); if (nextEntry == null) return false; String name = nextEntry.getName(); if (name.equals(expectedEntryName)) { // save .java locally FileOutputStream javaFileStream = new FileOutputStream(javaFilePath); byte[] buf = new byte[1024]; int n; while ((n = zip.read(buf, 0, 1024)) > -1) javaFileStream.write(buf, 0, n); // compile it into .class file JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); int result = compiler.run(null, null, null, javaFilePath); System.out.println(result); return result == 0; } } } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:net.ftb.util.FileUtils.java
/** * Extracts given zip to given location// w ww.j a v a2 s .c o m * @param zipLocation - the location of the zip to be extracted * @param outputLocation - location to extract to */ public static void extractZipTo(String zipLocation, String outputLocation) { ZipInputStream zipinputstream = null; try { byte[] buf = new byte[1024]; zipinputstream = new ZipInputStream(new FileInputStream(zipLocation)); ZipEntry zipentry = zipinputstream.getNextEntry(); while (zipentry != null) { String entryName = zipentry.getName(); int n; if (!zipentry.isDirectory() && !entryName.equalsIgnoreCase("minecraft") && !entryName.equalsIgnoreCase(".minecraft") && !entryName.equalsIgnoreCase("instMods")) { new File(outputLocation + File.separator + entryName).getParentFile().mkdirs(); FileOutputStream fileoutputstream = new FileOutputStream( outputLocation + File.separator + entryName); while ((n = zipinputstream.read(buf, 0, 1024)) > -1) { fileoutputstream.write(buf, 0, n); } fileoutputstream.close(); } zipinputstream.closeEntry(); zipentry = zipinputstream.getNextEntry(); } } catch (Exception e) { Logger.logError("Error while extracting zip", e); backupExtract(zipLocation, outputLocation); } finally { try { zipinputstream.close(); } catch (IOException e) { } } }
From source file:com.github.alexfalappa.nbspringboot.projects.initializr.InitializrProjectWizardIterator.java
private static void unZipFile(InputStream source, FileObject projectRoot, boolean removeMvnWrapper) throws IOException { try {/*from w w w . j a va 2 s .c o m*/ ZipInputStream str = new ZipInputStream(source); ZipEntry entry; while ((entry = str.getNextEntry()) != null) { final String entryName = entry.getName(); // optionally skip entries related to maven wrapper if (removeMvnWrapper && (entryName.contains(".mvn") || entryName.contains("mvnw"))) { continue; } if (entry.isDirectory()) { FileUtil.createFolder(projectRoot, entryName); } else { FileObject fo = FileUtil.createData(projectRoot, entryName); if ("nbproject/project.xml".equals(entryName)) { // Special handling for setting name of Ant-based projects; customize as needed: filterProjectXML(fo, str, projectRoot.getName()); } else { writeFile(str, fo); } } } } finally { source.close(); } }
From source file:org.calrissian.restdoclet.writer.swagger.SwaggerWriter.java
private static void copySwagger() throws IOException { ZipInputStream swaggerZip = null; FileOutputStream out = null;//from www .ja va2s . c o m try { swaggerZip = new ZipInputStream( Thread.currentThread().getContextClassLoader().getResourceAsStream(SWAGGER_UI_ARTIFACT)); ZipEntry entry; while ((entry = swaggerZip.getNextEntry()) != null) { final File swaggerFile = new File(".", entry.getName()); if (entry.isDirectory()) { if (!swaggerFile.isDirectory() && !swaggerFile.mkdirs()) { throw new RuntimeException("Unable to create directory: " + swaggerFile); } } else { copy(swaggerZip, new FileOutputStream(swaggerFile)); } } } finally { close(swaggerZip, out); } }