List of usage examples for org.apache.commons.compress.archivers.zip ZipArchiveEntry ZipArchiveEntry
public ZipArchiveEntry(File inputFile, String entryName)
From source file:com.glaf.core.util.ZipUtils.java
/** * /* w w w.j av a2 s . co m*/ * ?zip? * * @param files * ? * * @param zipFilePath * ?zip ,"/var/data/aa.zip"; */ public static void compressFile(File[] files, String zipFilePath) { if (files != null && files.length > 0) { if (isEndsWithZip(zipFilePath)) { ZipArchiveOutputStream zaos = null; try { File zipFile = new File(zipFilePath); zaos = new ZipArchiveOutputStream(zipFile); // Use Zip64 extensions for all entries where they are // required zaos.setUseZip64(Zip64Mode.AsNeeded); for (File file : files) { if (file != null) { ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(file, file.getName()); zaos.putArchiveEntry(zipArchiveEntry); InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[BUFFER]; int len = -1; while ((len = is.read(buffer)) != -1) { zaos.write(buffer, 0, len); } // Writes all necessary data for this entry. zaos.closeArchiveEntry(); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeStream(is); } } } zaos.finish(); } catch (Exception e) { throw new RuntimeException(e); } finally { IOUtils.closeStream(zaos); } } } }
From source file:com.neatresults.mgnltweaks.ui.action.ExportMultipleAction.java
/** * Once all items are exported, zip it all and send to client. *//*from www . ja v a2s . c om*/ @Override protected void onPostExecute() throws Exception { IOUtils.closeQuietly(fileOutputStream); postExecCount++; if (getItems().size() > 1) { ExportCommand exportCommand = (ExportCommand) getCommand(); String fileName = exportCommand.getFileName(); tempFiles.put(fileName, fileOutput); } if (getItems().size() > 1 && postExecCount == getItems().size()) { // last run on multi-run String fileName = "magnoliaExport.zip"; String mimeType = MIMEMapping.getMIMEType("zip"); // will get deleted by stream after it is streamed through http request TempFileStreamResource tempFileStreamResource = new TempFileStreamResource(); tempFileStreamResource.setTempFileName("magnoliaExport" + (Math.random() * 1000)); tempFileStreamResource.setTempFileExtension("zip"); ArchiveOutputStream zipOutput = new ArchiveStreamFactory().createArchiveOutputStream("zip", tempFileStreamResource.getTempFileOutputStream()); try { for (Entry<String, File> entry : tempFiles.entrySet()) { zipOutput.putArchiveEntry(new ZipArchiveEntry(entry.getValue(), entry.getKey())); FileInputStream fis = new FileInputStream(entry.getValue()); IOUtils.copy(fis, zipOutput); zipOutput.closeArchiveEntry(); IOUtils.closeQuietly(fis); } } finally { zipOutput.finish(); IOUtils.closeQuietly(zipOutput); } tempFileStreamResource.setFilename(fileName); tempFileStreamResource.setMIMEType(mimeType); // is this really necessary? tempFileStreamResource.getStream().setParameter("Content-Disposition", "attachment; filename=" + fileName + "\""); // Opens the resource for download Page.getCurrent().open(tempFileStreamResource, "", true); } else if (getItems().size() == 1) { // single item run final ExportCommand exportCommand = (ExportCommand) getCommand(); tempFileStreamResource.setFilename(exportCommand.getFileName()); tempFileStreamResource.setMIMEType(exportCommand.getMimeExtension()); // Opens the resource for download Page.getCurrent().open(tempFileStreamResource, "", true); } }
From source file:com.ibm.streamsx.topology.internal.context.remote.ZippedToolkitRemoteContext.java
private static void addAllToZippedArchive(Map<Path, String> starts, Path zipFilePath) throws IOException { try (ZipArchiveOutputStream zos = new ZipArchiveOutputStream(zipFilePath.toFile())) { for (Path start : starts.keySet()) { final String rootEntryName = starts.get(start); Files.walkFileTree(start, new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { // Skip pyc files. if (file.getFileName().toString().endsWith(".pyc")) return FileVisitResult.CONTINUE; String entryName = rootEntryName; String relativePath = start.relativize(file).toString(); // If empty, file is the start file. if (!relativePath.isEmpty()) { entryName = entryName + "/" + relativePath; }/*from www . j a v a 2 s . c om*/ // Zip uses forward slashes entryName = entryName.replace(File.separatorChar, '/'); ZipArchiveEntry entry = new ZipArchiveEntry(file.toFile(), entryName); if (Files.isExecutable(file)) entry.setUnixMode(0100770); else entry.setUnixMode(0100660); zos.putArchiveEntry(entry); Files.copy(file, zos); zos.closeArchiveEntry(); return FileVisitResult.CONTINUE; } public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { final String dirName = dir.getFileName().toString(); // Don't include pyc files or .toolkit if (dirName.equals("__pycache__")) return FileVisitResult.SKIP_SUBTREE; ZipArchiveEntry dirEntry = new ZipArchiveEntry(dir.toFile(), rootEntryName + "/" + start.relativize(dir).toString().replace(File.separatorChar, '/') + "/"); zos.putArchiveEntry(dirEntry); zos.closeArchiveEntry(); return FileVisitResult.CONTINUE; } }); } } }
From source file:fr.gael.dhus.datastore.processing.impl.ProcessProductPrepareDownload.java
/** * Creates a zip entry for the path specified with a name built from the base * passed in and the file/directory name. If the path is a directory, a * recursive call is made such that the full directory is added to the zip. * * @param zOut The zip file's output stream * @param path The filesystem path of the file/directory being added * @param base The base prefix to for the name of the zip file entry * * @throws IOException If anything goes wrong *//* w w w. ja va 2 s .c o m*/ private static void addFileToZip(ZipArchiveOutputStream zOut, String path, String base) throws IOException { File f = new File(path); String entryName = base + f.getName(); ZipArchiveEntry zipEntry = new ZipArchiveEntry(f, entryName); zOut.putArchiveEntry(zipEntry); if (f.isFile()) { FileInputStream fInputStream = null; try { fInputStream = new FileInputStream(f); IOUtils.copy(fInputStream, zOut, 65535); zOut.closeArchiveEntry(); } finally { fInputStream.close(); } } else { zOut.closeArchiveEntry(); File[] children = f.listFiles(); if (children != null) { for (File child : children) { logger.debug("ZIP Adding " + child.getName()); addFileToZip(zOut, child.getAbsolutePath(), entryName + "/"); } } } }
From source file:com.github.braully.graph.DatabaseFacade.java
private static void addFileToZip(ZipArchiveOutputStream zOut, String path, String base) throws IOException { File f = new File(path); String entryName = base + f.getName(); ZipArchiveEntry zipEntry = new ZipArchiveEntry(f, entryName); zOut.putArchiveEntry(zipEntry);/*from w w w. jav a 2 s . c om*/ if (f.isFile()) { FileInputStream fInputStream = null; try { fInputStream = new FileInputStream(f); IOUtils.copy(fInputStream, zOut); zOut.closeArchiveEntry(); } finally { IOUtils.closeQuietly(fInputStream); } } else { zOut.closeArchiveEntry(); File[] children = f.listFiles(); if (children != null) { for (File child : children) { addFileToZip(zOut, child.getAbsolutePath(), entryName + "/"); } } } }
From source file:ching.icecreaming.action.ViewAction.java
@Action(value = "view", results = { @Result(name = "login", location = "edit.jsp"), @Result(name = "input", location = "view.jsp"), @Result(name = "success", location = "view.jsp"), @Result(name = "error", location = "error.jsp") }) public String execute() throws Exception { Enumeration enumerator = null; String[] array1 = null, array2 = null; int int1 = -1, int2 = -1, int3 = -1; InputStream inputStream1 = null; OutputStream outputStream1 = null; java.io.File file1 = null, file2 = null, dir1 = null; List<File> files = null; HttpHost httpHost1 = null;//from w ww .j a v a2 s .co m HttpGet httpGet1 = null, httpGet2 = null; HttpPut httpPut1 = null; URI uri1 = null; URL url1 = null; DefaultHttpClient httpClient1 = null; URIBuilder uriBuilder1 = null, uriBuilder2 = null; HttpResponse httpResponse1 = null, httpResponse2 = null; HttpEntity httpEntity1 = null, httpEntity2 = null; List<NameValuePair> nameValuePair1 = null; String string1 = null, string2 = null, string3 = null, string4 = null, return1 = LOGIN; XMLConfiguration xmlConfiguration = null; List<HierarchicalConfiguration> list1 = null, list2 = null; HierarchicalConfiguration hierarchicalConfiguration2 = null; DataModel1 dataModel1 = null; DataModel2 dataModel2 = null; List<DataModel1> listObject1 = null, listObject3 = null; org.joda.time.DateTime dateTime1 = null, dateTime2 = null; org.joda.time.Period period1 = null; PeriodFormatter periodFormatter1 = new PeriodFormatterBuilder().appendYears() .appendSuffix(String.format(" %s", getText("year")), String.format(" %s", getText("years"))) .appendSeparator(" ").appendMonths() .appendSuffix(String.format(" %s", getText("month")), String.format(" %s", getText("months"))) .appendSeparator(" ").appendWeeks() .appendSuffix(String.format(" %s", getText("week")), String.format(" %s", getText("weeks"))) .appendSeparator(" ").appendDays() .appendSuffix(String.format(" %s", getText("day")), String.format(" %s", getText("days"))) .appendSeparator(" ").appendHours() .appendSuffix(String.format(" %s", getText("hour")), String.format(" %s", getText("hours"))) .appendSeparator(" ").appendMinutes() .appendSuffix(String.format(" %s", getText("minute")), String.format(" %s", getText("minutes"))) .appendSeparator(" ").appendSeconds().minimumPrintedDigits(2) .appendSuffix(String.format(" %s", getText("second")), String.format(" %s", getText("seconds"))) .printZeroNever().toFormatter(); if (StringUtils.isBlank(urlString) || StringUtils.isBlank(wsType)) { urlString = portletPreferences.getValue("urlString", "/"); wsType = portletPreferences.getValue("wsType", "folder"); } Configuration propertiesConfiguration1 = new PropertiesConfiguration("system.properties"); timeZone1 = portletPreferences.getValue("timeZone", TimeZone.getDefault().getID()); enumerator = portletPreferences.getNames(); if (enumerator.hasMoreElements()) { array1 = portletPreferences.getValues("server", null); if (array1 != null) { if (ArrayUtils.isNotEmpty(array1)) { for (int1 = 0; int1 < array1.length; int1++) { switch (int1) { case 0: sid = array1[int1]; break; case 1: uid = array1[int1]; break; case 2: pid = array1[int1]; break; case 3: alias1 = array1[int1]; break; default: break; } } sid = new String(Base64.decodeBase64(sid.getBytes())); uid = new String(Base64.decodeBase64(uid.getBytes())); pid = new String(Base64.decodeBase64(pid.getBytes())); } return1 = INPUT; } else { return1 = LOGIN; } } else { return1 = LOGIN; } if (StringUtils.equals(urlString, "/")) { if (listObject1 != null) { listObject1.clear(); } if (session.containsKey("breadcrumbs")) { session.remove("breadcrumbs"); } } else { array2 = StringUtils.split(urlString, "/"); listObject1 = (session.containsKey("breadcrumbs")) ? (List<DataModel1>) session.get("breadcrumbs") : new ArrayList<DataModel1>(); int2 = array2.length - listObject1.size(); if (int2 > 0) { listObject1.add(new DataModel1(urlString, label1)); } else { int2 += listObject1.size(); for (int1 = listObject1.size() - 1; int1 >= int2; int1--) { listObject1.remove(int1); } } session.put("breadcrumbs", listObject1); } switch (wsType) { case "folder": break; case "reportUnit": try { dateTime1 = new org.joda.time.DateTime(); return1 = INPUT; httpClient1 = new DefaultHttpClient(); if (StringUtils.equals(button1, getText("Print"))) { nameValuePair1 = new ArrayList<NameValuePair>(); if (listObject2 != null) { if (listObject2.size() > 0) { for (DataModel2 dataObject2 : listObject2) { listObject3 = dataObject2.getOptions(); if (listObject3 == null) { string2 = dataObject2.getValue1(); if (StringUtils.isNotBlank(string2)) nameValuePair1.add(new BasicNameValuePair(dataObject2.getId(), string2)); } else { for (int1 = listObject3.size() - 1; int1 >= 0; int1--) { dataModel1 = (DataModel1) listObject3.get(int1); string2 = dataModel1.getString2(); if (StringUtils.isNotBlank(string2)) nameValuePair1 .add(new BasicNameValuePair(dataObject2.getId(), string2)); } } } } } url1 = new URL(sid); uriBuilder1 = new URIBuilder(sid); uriBuilder1.setUserInfo(uid, pid); if (StringUtils.isBlank(format1)) format1 = "pdf"; uriBuilder1.setPath(url1.getPath() + "/rest_v2/reports" + urlString + "." + format1); if (StringUtils.isNotBlank(locale2)) { nameValuePair1.add(new BasicNameValuePair("userLocale", locale2)); } if (StringUtils.isNotBlank(page1)) { if (NumberUtils.isNumber(page1)) { nameValuePair1.add(new BasicNameValuePair("page", page1)); } } if (nameValuePair1.size() > 0) { uriBuilder1.setQuery(URLEncodedUtils.format(nameValuePair1, "UTF-8")); } uri1 = uriBuilder1.build(); httpGet1 = new HttpGet(uri1); httpResponse1 = httpClient1.execute(httpGet1); int1 = httpResponse1.getStatusLine().getStatusCode(); if (int1 == HttpStatus.SC_OK) { string3 = System.getProperty("java.io.tmpdir") + File.separator + httpServletRequest.getSession().getId(); dir1 = new File(string3); if (!dir1.exists()) { dir1.mkdir(); } httpEntity1 = httpResponse1.getEntity(); file1 = new File(string3, StringUtils.substringAfterLast(urlString, "/") + "." + format1); if (StringUtils.equalsIgnoreCase(format1, "html")) { result1 = EntityUtils.toString(httpEntity1); FileUtils.writeStringToFile(file1, result1); array1 = StringUtils.substringsBetween(result1, "<img src=\"", "\""); if (ArrayUtils.isNotEmpty(array1)) { dir1 = new File( string3 + File.separator + FilenameUtils.getBaseName(file1.getName())); if (dir1.exists()) { FileUtils.deleteDirectory(dir1); } file2 = new File(FilenameUtils.getFullPath(file1.getAbsolutePath()) + FilenameUtils.getBaseName(file1.getName()) + ".zip"); if (file2.exists()) { if (FileUtils.deleteQuietly(file2)) { } } for (int2 = 0; int2 < array1.length; int2++) { try { string2 = url1.getPath() + "/rest_v2/reports" + urlString + "/" + StringUtils.substringAfter(array1[int2], "/"); uriBuilder1.setPath(string2); uri1 = uriBuilder1.build(); httpGet1 = new HttpGet(uri1); httpResponse1 = httpClient1.execute(httpGet1); int1 = httpResponse1.getStatusLine().getStatusCode(); } finally { if (int1 == HttpStatus.SC_OK) { try { string2 = StringUtils.substringBeforeLast(array1[int2], "/"); dir1 = new File(string3 + File.separator + string2); if (!dir1.exists()) { dir1.mkdirs(); } httpEntity1 = httpResponse1.getEntity(); inputStream1 = httpEntity1.getContent(); } finally { string1 = StringUtils.substringAfterLast(array1[int2], "/"); file2 = new File(string3 + File.separator + string2, string1); outputStream1 = new FileOutputStream(file2); IOUtils.copy(inputStream1, outputStream1); } } } } outputStream1 = new FileOutputStream( FilenameUtils.getFullPath(file1.getAbsolutePath()) + FilenameUtils.getBaseName(file1.getName()) + ".zip"); ArchiveOutputStream archiveOutputStream1 = new ArchiveStreamFactory() .createArchiveOutputStream(ArchiveStreamFactory.ZIP, outputStream1); archiveOutputStream1.putArchiveEntry(new ZipArchiveEntry(file1, file1.getName())); IOUtils.copy(new FileInputStream(file1), archiveOutputStream1); archiveOutputStream1.closeArchiveEntry(); dir1 = new File(FilenameUtils.getFullPath(file1.getAbsolutePath()) + FilenameUtils.getBaseName(file1.getName())); files = (List<File>) FileUtils.listFiles(dir1, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE); for (File file3 : files) { archiveOutputStream1.putArchiveEntry(new ZipArchiveEntry(file3, StringUtils .substringAfter(file3.getCanonicalPath(), string3 + File.separator))); IOUtils.copy(new FileInputStream(file3), archiveOutputStream1); archiveOutputStream1.closeArchiveEntry(); } archiveOutputStream1.close(); } bugfixGateIn = propertiesConfiguration1.getBoolean("bugfixGateIn", false); string4 = bugfixGateIn ? String.format("<img src=\"%s/namespace1/file-link?sessionId=%s&fileName=", portletRequest.getContextPath(), httpServletRequest.getSession().getId()) : String.format("<img src=\"%s/namespace1/file-link?fileName=", portletRequest.getContextPath()); result1 = StringUtils.replace(result1, "<img src=\"", string4); } else { inputStream1 = httpEntity1.getContent(); outputStream1 = new FileOutputStream(file1); IOUtils.copy(inputStream1, outputStream1); result1 = file1.getAbsolutePath(); } return1 = SUCCESS; } else { addActionError(String.format("%s %d: %s", getText("Error"), int1, getText(Integer.toString(int1)))); } dateTime2 = new org.joda.time.DateTime(); period1 = new Period(dateTime1, dateTime2.plusSeconds(1)); message1 = getText("Execution.time") + ": " + periodFormatter1.print(period1); } else { url1 = new URL(sid); uriBuilder1 = new URIBuilder(sid); uriBuilder1.setUserInfo(uid, pid); uriBuilder1.setPath(url1.getPath() + "/rest_v2/reports" + urlString + "/inputControls"); uri1 = uriBuilder1.build(); httpGet1 = new HttpGet(uri1); httpResponse1 = httpClient1.execute(httpGet1); int1 = httpResponse1.getStatusLine().getStatusCode(); switch (int1) { case HttpStatus.SC_NO_CONTENT: break; case HttpStatus.SC_OK: httpEntity1 = httpResponse1.getEntity(); if (httpEntity1 != null) { inputStream1 = httpEntity1.getContent(); if (inputStream1 != null) { xmlConfiguration = new XMLConfiguration(); xmlConfiguration.load(inputStream1); list1 = xmlConfiguration.configurationsAt("inputControl"); if (list1.size() > 0) { listObject2 = new ArrayList<DataModel2>(); for (HierarchicalConfiguration hierarchicalConfiguration1 : list1) { string2 = hierarchicalConfiguration1.getString("type"); dataModel2 = new DataModel2(); dataModel2.setId(hierarchicalConfiguration1.getString("id")); dataModel2.setLabel1(hierarchicalConfiguration1.getString("label")); dataModel2.setType1(string2); dataModel2.setMandatory(hierarchicalConfiguration1.getBoolean("mandatory")); dataModel2.setReadOnly(hierarchicalConfiguration1.getBoolean("readOnly")); dataModel2.setVisible(hierarchicalConfiguration1.getBoolean("visible")); switch (string2) { case "bool": case "singleValueText": case "singleValueNumber": case "singleValueDate": case "singleValueDatetime": hierarchicalConfiguration2 = hierarchicalConfiguration1 .configurationAt("state"); dataModel2.setValue1(hierarchicalConfiguration2.getString("value")); break; case "singleSelect": case "singleSelectRadio": case "multiSelect": case "multiSelectCheckbox": hierarchicalConfiguration2 = hierarchicalConfiguration1 .configurationAt("state"); list2 = hierarchicalConfiguration2.configurationsAt("options.option"); if (list2.size() > 0) { listObject3 = new ArrayList<DataModel1>(); for (HierarchicalConfiguration hierarchicalConfiguration3 : list2) { dataModel1 = new DataModel1( hierarchicalConfiguration3.getString("label"), hierarchicalConfiguration3.getString("value")); if (hierarchicalConfiguration3.getBoolean("selected")) { dataModel2.setValue1( hierarchicalConfiguration3.getString("value")); } listObject3.add(dataModel1); } dataModel2.setOptions(listObject3); } break; default: break; } listObject2.add(dataModel2); } } } } break; default: addActionError(String.format("%s %d: %s", getText("Error"), int1, getText(Integer.toString(int1)))); break; } if (httpEntity1 != null) { EntityUtils.consume(httpEntity1); } uriBuilder1.setPath(url1.getPath() + "/rest/resource" + urlString); uri1 = uriBuilder1.build(); httpGet1 = new HttpGet(uri1); httpResponse1 = httpClient1.execute(httpGet1); int2 = httpResponse1.getStatusLine().getStatusCode(); if (int2 == HttpStatus.SC_OK) { httpEntity1 = httpResponse1.getEntity(); inputStream1 = httpEntity1.getContent(); xmlConfiguration = new XMLConfiguration(); xmlConfiguration.load(inputStream1); list1 = xmlConfiguration.configurationsAt("resourceDescriptor"); for (HierarchicalConfiguration hierarchicalConfiguration4 : list1) { if (StringUtils.equalsIgnoreCase( StringUtils.trim(hierarchicalConfiguration4.getString("[@wsType]")), "prop")) { if (map1 == null) map1 = new HashMap<String, String>(); string2 = StringUtils.substringBetween( StringUtils.substringAfter( hierarchicalConfiguration4.getString("[@uriString]"), "_files/"), "_", ".properties"); map1.put(string2, StringUtils.isBlank(string2) ? getText("Default") : getText(string2)); } } } if (httpEntity1 != null) { EntityUtils.consume(httpEntity1); } } } catch (IOException | ConfigurationException | URISyntaxException exception1) { exception1.printStackTrace(); addActionError(exception1.getLocalizedMessage()); httpGet1.abort(); return ERROR; } finally { httpClient1.getConnectionManager().shutdown(); IOUtils.closeQuietly(inputStream1); } break; default: addActionError(getText("This.file.type.is.not.supported")); break; } if (return1 != LOGIN) { sid = new String(Base64.encodeBase64(sid.getBytes())); uid = new String(Base64.encodeBase64(uid.getBytes())); pid = new String(Base64.encodeBase64(pid.getBytes())); } return return1; }
From source file:com.citytechinc.cq.component.maven.util.ComponentMojoUtil.java
/** * Writes a provided file to a provided archive output stream at a path * determined by the class of the component. * //w ww .ja v a 2s .co m * @param file * @param componentClass * @param archiveStream * @param reservedNames A list of files which already exist within the Zip * Archive. If a file already exists for a particular component, * it is left untouched. * @param componentPathBase * @throws IOException * @throws ClassNotFoundException */ public static void writeElementToArchiveFile(ComponentNameTransformer transformer, File file, CtClass componentClass, ZipArchiveOutputStream archiveStream, Set<String> reservedNames, String componentPathBase, String defaultComponentPathSuffix, String path) throws IOException, ClassNotFoundException { String editConfigFilePath = ComponentMojoUtil.getComponentBasePathForComponentClass(componentClass, componentPathBase) + "/" + ComponentMojoUtil.getComponentPathSuffixForComponentClass(componentClass, defaultComponentPathSuffix) + "/" + ComponentMojoUtil.getComponentNameForComponentClass(transformer, componentClass) + path; if (!reservedNames.contains(editConfigFilePath.toLowerCase())) { ZipArchiveEntry entry = new ZipArchiveEntry(file, editConfigFilePath); archiveStream.putArchiveEntry(entry); IOUtils.copy(new FileInputStream(file), archiveStream); archiveStream.closeArchiveEntry(); } else { ComponentMojoUtil.getLog().debug("Existing file found at " + editConfigFilePath); } }
From source file:fr.gael.dhus.datastore.processing.ProcessingManager.java
/** * Creates a zip entry for the path specified with a name built from the base * passed in and the file/directory name. If the path is a directory, a * recursive call is made such that the full directory is added to the zip. * * @param z_out The zip file's output stream * @param path The filesystem path of the file/directory being added * @param base The base prefix to for the name of the zip file entry * @throws IOException If anything goes wrong */// ww w . j ava 2 s . c om private void addFileToZip(ZipArchiveOutputStream z_out, String path, String base) throws IOException { File f = new File(path); String entryName = base + f.getName(); ZipArchiveEntry zipEntry = new ZipArchiveEntry(f, entryName); z_out.putArchiveEntry(zipEntry); if (f.isFile()) { FileInputStream fInputStream = null; try { fInputStream = new FileInputStream(f); org.apache.commons.compress.utils.IOUtils.copy(fInputStream, z_out, 65535); z_out.closeArchiveEntry(); } finally { fInputStream.close(); } } else { z_out.closeArchiveEntry(); File[] children = f.listFiles(); if (children != null) { for (File child : children) { LOGGER.debug("ZIP Adding " + child.getName()); addFileToZip(z_out, child.getAbsolutePath(), entryName + "/"); } } } }
From source file:net.test.aliyun.z7.Task.java
public void doWork() throws Throwable { //init task to DB System.out.println("do Task " + index + "\t from :" + oldKey); ////from w w w . jav a2 s. c o m //1. System.out.print("\t save to Local -> working... "); OSSObject ossObject = client.getObject("files-subtitle", oldKey); File rarFile = new File(this.tempPath, ossObject.getObjectMetadata().getContentDisposition()); rarFile.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(rarFile, false); InputStream inStream = ossObject.getObjectContent(); IOUtils.copy(inStream, fos); fos.flush(); fos.close(); System.out.print("-> finish.\n"); // //2. System.out.print("\t extract rar -> working... "); String extToosHome = "C:\\Program Files (x86)\\7-Zip"; String rarFileStr = rarFile.getAbsolutePath(); String toDir = rarFileStr.substring(0, rarFileStr.length() - ".rar".length()); // // int extract = Zip7Object.extract(extToosHome, rarFile.getAbsolutePath(), toDir); if (extract != 0) { if (extract != 2) System.out.println(); FileUtils.deleteDir(new File(toDir)); rarFile.delete(); throw new Exception("extract error."); } System.out.print("-> finish.\n"); // //3. System.out.print("\t package zip-> working... "); String zipFileName = rarFile.getAbsolutePath(); zipFileName = zipFileName.substring(0, zipFileName.length() - ".rar".length()) + ".zip"; ZipArchiveOutputStream outStream = new ZipArchiveOutputStream(new File(zipFileName)); outStream.setEncoding("GBK"); Iterator<File> itFile = FileUtils.iterateFiles(new File(toDir), FileFilterUtils.fileFileFilter(), FileFilterUtils.directoryFileFilter()); StringBuffer buffer = new StringBuffer(); while (itFile.hasNext()) { File it = itFile.next(); if (it.isDirectory()) continue; String entName = it.getAbsolutePath().substring(toDir.length() + 1); ZipArchiveEntry ent = new ZipArchiveEntry(it, entName); outStream.putArchiveEntry(ent); InputStream itInStream = new FileInputStream(it); IOUtils.copy(itInStream, outStream); itInStream.close(); outStream.flush(); outStream.closeArchiveEntry(); buffer.append(ent.getName()); } outStream.flush(); outStream.close(); System.out.print("-> finish.\n"); // //4. FileUtils.deleteDir(new File(toDir)); System.out.print("\t delete temp dir -> finish.\n"); // //5.save to System.out.print("\t save to oss -> working... "); ObjectMetadata omd = ossObject.getObjectMetadata(); String contentDisposition = omd.getContentDisposition(); contentDisposition = contentDisposition.substring(0, contentDisposition.length() - ".rar".length()) + ".zip"; omd.setContentDisposition(contentDisposition); omd.setContentLength(new File(zipFileName).length()); InputStream zipInStream = new FileInputStream(zipFileName); PutObjectResult result = client.putObject("files-subtitle-format-zip", newKey, zipInStream, omd); zipInStream.close(); new File(zipFileName).delete(); System.out.print("-> OK:" + result.getETag()); System.out.print("-> finish.\n"); // //6.save files info int res = jdbc.update("update `oss-subtitle` set files=? , size=? , lastTime=now() where oss_key =?", buffer.toString(), omd.getContentLength(), newKey); System.out.println("\t save info to db -> " + res); }
From source file:org.apache.openejb.maven.plugin.BuildTomEEMojo.java
private void zip(final ZipArchiveOutputStream zip, final File f, final String prefix) throws IOException { final String path = f.getPath().replace(prefix, "").replace(File.separator, "/"); final ZipArchiveEntry archiveEntry = new ZipArchiveEntry(f, path); if (isSh(path)) { archiveEntry.setUnixMode(0755);/*from w w w . j a v a2 s .c o m*/ } zip.putArchiveEntry(archiveEntry); if (f.isDirectory()) { zip.closeArchiveEntry(); final File[] files = f.listFiles(); if (files != null) { for (final File child : files) { zip(zip, child, prefix); } } } else { IO.copy(f, zip); zip.closeArchiveEntry(); } }