Example usage for java.util.zip ZipFile getName

List of usage examples for java.util.zip ZipFile getName

Introduction

In this page you can find the example usage for java.util.zip ZipFile getName.

Prototype

public String getName() 

Source Link

Document

Returns the path name of the ZIP file.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    ZipFile zipFile = new ZipFile(new File("testfile.zip"), ZipFile.OPEN_READ);

    System.out.println(zipFile.getName());
}

From source file:com.mc.printer.model.utils.ZipHelper.java

public static void unZip(String sourceZip, String outDirName) throws IOException {
    log.info("unzip source:" + sourceZip);
    log.info("unzip to :" + outDirName);
    ZipFile zfile = new ZipFile(sourceZip);
    System.out.println(zfile.getName());
    Enumeration zList = zfile.entries();
    ZipEntry ze = null;/*from  w  w  w.  j av a2 s .c o  m*/
    byte[] buf = new byte[1024];
    while (zList.hasMoreElements()) {
        //ZipFileZipEntry
        ze = (ZipEntry) zList.nextElement();
        if (ze.isDirectory()) {
            continue;
        }
        //ZipEntry?InputStreamOutputStream
        File fil = getRealFileName(outDirName, ze.getName());

        OutputStream os = new BufferedOutputStream(new FileOutputStream(fil));
        InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
        int readLen = 0;
        while ((readLen = is.read(buf, 0, 1024)) != -1) {
            os.write(buf, 0, readLen);
        }
        is.close();
        os.close();
        log.debug("Extracted: " + ze.getName());
    }
    zfile.close();

}

From source file:org.easysoa.registry.frascati.FileUtils.java

/**
 * Unzips the given jar in a temp file and returns its files' URLs Inspired
 * from AssemblyFactoryManager.processContribution() (though doesn't add it
 * to the classloader or parse composites)
 * TODO move to util TODO better : delete temp files afterwards (or mark them so) OR rather use jar:url ?
 * @param SCA zip or jar/*from w ww.  j  a  va  2  s  .c o m*/
 * @return unzipped composites URLs
 * @throws ManagerException
 */
public static final Set<URL> unzipAndGetFileUrls(File file) {
    try {
        // Load contribution zip file
        ZipFile zipFile = new ZipFile(file);

        // Get folder name for output
        final String folder = zipFile.getName().substring(zipFile.getName().lastIndexOf(File.separator),
                zipFile.getName().length() - ".zip".length());

        Set<URL> fileURLSet = new HashSet<URL>();

        // Set directory for extracted files

        // TODO : use system temp directory but should use output folder
        // given by
        // runtime component. Will be possible once Assembly Factory modules
        // will
        // be merged

        final String tempDir = System.getProperty("java.io.tmpdir") + File.separator + folder + File.separator;

        Enumeration<? extends ZipEntry> entries = zipFile.entries();

        // Iterate over zip entries
        while (entries.hasMoreElements()) {
            ZipEntry entry = entries.nextElement();

            log.info("ZIP entry: " + entry.getName());

            // create directories
            if (entry.isDirectory()) {
                log.info("create directory : " + tempDir + entry.getName());
                new File(tempDir, entry.getName()).mkdirs();
            } else {
                File f = new File(tempDir, File.separator + entry.getName());
                // register jar files
                int idx = entry.getName().lastIndexOf(File.separator);
                if (idx != -1) {
                    String tmp = entry.getName().substring(0, idx);
                    log.info("create directory : " + tempDir + tmp);
                    new File(tempDir, tmp).mkdirs();
                }
                // extract entry from zip to tempDir
                copy(zipFile.getInputStream(entry), new BufferedOutputStream(new FileOutputStream(f)));
                // add to res set
                fileURLSet.add(f.toURI().toURL());
            }
        }

        return fileURLSet;

    } catch (IOException e) {
        log.error(e);
        return new HashSet<URL>(0);
    }
}

From source file:org.talend.dataprofiler.ecos.jobs.ComponentInstaller.java

/**
 * Unzip the component file to user folder.
 * //from   w ww. jav  a2s  .  c  om
 * @param zipFile The component zip file
 * @param targetFolder The user folder
 * @return
 * @throws Exception
 */
public static File unzip(String zipFile, String targetFolder) throws Exception {

    ZipFile zip = new ZipFile(zipFile);

    // folder that contains all the unzipped files
    File rootFolder = getRootFolder(zip, targetFolder);

    if (rootFolder == null) {
        // the zip does not have any directory, fix it
        String fileName = zip.getName().substring(zip.getName().lastIndexOf(File.separatorChar) + 1);
        fileName = fileName.substring(0, fileName.lastIndexOf('.')); // remove extension
        rootFolder = new File(targetFolder, fileName);
        targetFolder = targetFolder + File.separatorChar + fileName;
    }

    if (rootFolder.exists()) {
        // we have installed older revision, delete it
        FileUtils.deleteDirectory(rootFolder);
    }
    rootFolder.mkdir();
    // move some common use codes for unzipping file to FilesUtils
    FilesUtils.unzip(zipFile, targetFolder);

    return rootFolder;
}

From source file:org.eclipse.recommenders.utils.Zips.java

/**
 * Closes the give zip. Exceptions are printed to System.err.
 *///  w  ww. ja  va2s .  c o m
public static boolean closeQuietly(ZipFile z) {
    if (z == null) {
        return true;
    }
    try {
        z.close();
        return true;
    } catch (IOException e) {
        System.err.printf("Failed to close zip '%s'. Caught exception printed below.\n", z.getName());
        e.printStackTrace();
        return false;
    }
}

From source file:org.talend.designer.components.exchange.jobs.ComponentInstaller.java

/**
 * Unzip the component file to user folder.
 * //from   w  ww . jav  a 2  s  .co m
 * @param zipFile The component zip file
 * @param targetFolder The user folder
 * @return
 * @throws Exception
 */
@SuppressWarnings("unchecked")
public static File unzip(String zipFile, String targetFolder) throws Exception {

    ZipFile zip = new ZipFile(zipFile);

    // folder that contains all the unzipped files
    File rootFolder = getRootFolder(zip, targetFolder);

    if (rootFolder == null) {
        // the zip does not have any directory, fix it
        String fileName = new File(zip.getName()).getName();
        fileName = fileName.substring(0, fileName.lastIndexOf('.')); // remove extension
        Pattern pattern = Pattern.compile("^([\\w]*)");
        Matcher matcher = pattern.matcher(fileName);
        if (matcher.find()) {
            fileName = matcher.group(1);
        }
        rootFolder = new File(targetFolder, fileName);
        targetFolder = targetFolder + File.separatorChar + fileName;
    }

    if (rootFolder.exists()) {
        // we have installed older revision, delete it
        FileUtils.deleteDirectory(rootFolder);
    }
    rootFolder.mkdir();
    // move some common use codes for unzipping file to FilesUtils
    FilesUtils.unzip(zipFile, targetFolder);
    boolean valid = false;
    if (GlobalServiceRegister.getDefault().isServiceRegistered(IComponentsLocalProviderService.class)) {
        IComponentsLocalProviderService service = (IComponentsLocalProviderService) GlobalServiceRegister
                .getDefault().getService(IComponentsLocalProviderService.class);
        if (service != null) {
            valid = service.validateComponent(rootFolder.getAbsolutePath(),
                    LanguageManager.getCurrentLanguage());
        }
    }

    if (!valid) {
        if (rootFolder.exists() && rootFolder.isDirectory()) {
            for (File f : rootFolder.listFiles()) {
                f.delete();
            }
            rootFolder.delete();
        }
        return null;
    }
    return rootFolder;
}

From source file:pl.betoncraft.betonquest.editor.model.PackageSet.java

public static PackageSet loadFromZip(ZipFile file) throws IOException, PackageNotFoundException {
    HashMap<String, HashMap<String, InputStream>> setMap = new HashMap<>();
    Enumeration<? extends ZipEntry> entries = file.entries();
    String setName = file.getName().substring(file.getName().lastIndexOf(File.separatorChar) + 1)
            .replace(".zip", "");
    // extract correct entries from the zip file
    while (true) {
        try {/*from  w w w  .j  ava2 s.  com*/
            ZipEntry entry = entries.nextElement();
            String entryName = entry.getName();
            // get the correct path separator (both can be used)
            char separator = (entryName.contains("/") ? '/' : '\\');
            // index of first separator used to get set name
            int index = entryName.indexOf(separator);
            // skip entry if there are no path separators (files in zip root like license, readme etc.)
            if (index < 0) {
                continue;
            }
            if (!entryName.endsWith(".yml")) {
                continue;
            }
            String[] parts = entryName.split(Pattern.quote(String.valueOf(separator)));
            String ymlName = parts[parts.length - 1].substring(0, parts[parts.length - 1].length() - 4);
            StringBuilder builder = new StringBuilder();
            int length = parts.length - 1;
            boolean conversation = false;
            if (parts[length - 1].equals("conversations")) {
                length--;
                conversation = true;
            }
            for (int i = 0; i < length; i++) {
                builder.append(parts[i] + '-');
            }
            String packName = builder.substring(0, builder.length() - 1);
            HashMap<String, InputStream> packMap = setMap.get(packName);
            if (packMap == null) {
                packMap = new HashMap<>();
                setMap.put(packName, packMap);
            }
            List<String> allowedNames = Arrays
                    .asList(new String[] { "main", "events", "conditions", "objectives", "journal", "items" });
            if (conversation) {
                packMap.put("conversations." + ymlName, file.getInputStream(entry));
            } else {
                if (allowedNames.contains(ymlName)) {
                    packMap.put(ymlName, file.getInputStream(entry));
                }
            }
        } catch (NoSuchElementException e) {
            break;
        }
    }
    PackageSet set = parseStreams(setName, setMap);
    BetonQuestEditor.getInstance().getSets().add(set);
    RootController.setPackages(BetonQuestEditor.getInstance().getSets());
    return set;
}

From source file:org.eclipse.che.plugin.gwt.Utils.java

/**
 * Reads content of the file from ZIP archive.
 *
 * @param zipFile ZIP file/*from   w  w w  .  ja  v a2  s.co m*/
 * @param path path of the file to read content
 * @return content of the file with the given path
 * @throws IOException if error occurs while reading
 * @throws IllegalArgumentException if file not found in ZIP archive
 */
public static String getFileContent(ZipFile zipFile, String path) throws IOException {
    Enumeration<? extends ZipEntry> entries = zipFile.entries();

    while (entries.hasMoreElements()) {
        ZipEntry entry = entries.nextElement();

        if (path.equals(entry.getName())) {
            try (InputStream in = zipFile.getInputStream(entry)) {
                byte[] bytes = IOUtils.toByteArray(in);

                return new String(bytes);
            }
        }
    }

    throw new IllegalArgumentException(format("Cannot find file '%s' in '%s'", path, zipFile.getName()));
}

From source file:net.sourceforge.dita4publishers.tools.dxp.DitaDxpHelper.java

/**
 * Extracts only the local dependencies used from a map from a DXP package.
 * @param zipFile/*  www. ja va 2 s.c o  m*/
 * @param mapEntry
 * @param outputDir
 * @param dxpOptions
 * @throws Exception 
 */
private static void extractMap(ZipFile zipFile, ZipEntry mapEntry, File outputDir,
        MapBosProcessorOptions dxpOptions) throws Exception {
    Map<URI, Document> domCache = new HashMap<URI, Document>();

    if (!dxpOptions.isQuiet())
        log.info("Extracting map " + mapEntry.getName() + "...");

    BosConstructionOptions bosOptions = new BosConstructionOptions(log, domCache);

    InputSource source = new InputSource(zipFile.getInputStream(mapEntry));

    File dxpFile = new File(zipFile.getName());

    URL baseUri = new URL("jar:" + dxpFile.toURI().toURL().toExternalForm() + "!/");
    URL mapUrl = new URL(baseUri, mapEntry.getName());

    source.setSystemId(mapUrl.toExternalForm());

    Document rootMap = DomUtil.getDomForSource(source, bosOptions, false);
    DitaBoundedObjectSet mapBos = DitaBosHelper.calculateMapBos(bosOptions, log, rootMap);

    MapCopyingBosVisitor visitor = new MapCopyingBosVisitor(outputDir);
    visitor.visit(mapBos);
    if (!dxpOptions.isQuiet())
        log.info("Map extracted.");
}

From source file:org.ambraproject.article.service.XslIngestArchiveProcessor.java

/**
 * Generate a description of the given zip archive.
 *
 * @param zip the zip archive to describe
 * @return the xml doc describing the archive (adheres to zip.dtd)
 * @throws IOException if an exception occurred reading the zip archive
 *///from  w w w  .j a v  a 2 s . c  o m
public static String describeZip(ZipFile zip) throws IOException {
    StringBuilder res = new StringBuilder(500);
    res.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    res.append("<ZipInfo");
    if (zip.getName() != null)
        res.append(" name=\"").append(attrEscape(zip.getName())).append("\"");
    res.append(">\n");

    Enumeration<? extends ZipEntry> entries = zip.entries();
    while (entries.hasMoreElements())
        entry2xml(entries.nextElement(), res);

    res.append("</ZipInfo>\n");
    return res.toString();
}