Example usage for java.util.zip ZipEntry getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the entry.

Usage

From source file:com.nuvolect.securesuite.util.OmniZip.java

/**
 * Unzip the file into the target directory.
 * The added structure is updated to reflect any new files and directories created.
 * Overwrite files when requested./*  w  w  w  .j a  v a  2 s.c o m*/
 * @param zipOmni
 * @param targetDir
 * @param added
 * @param httpIpPort
 * @return
 */
public static boolean unzipFile(OmniFile zipOmni, OmniFile targetDir, JsonArray added, String httpIpPort) {

    String volumeId = zipOmni.getVolumeId();
    String rootFolderPath = targetDir.getPath();
    boolean DEBUG = true;

    /**
     * Keep a list of all directories created.
     * Defer creating the directory object files until the zip is extracted.
     * This way the dir=1/0 settings can be set accurately.
     */
    ArrayList<OmniFile> directories = new ArrayList<>();

    ZipInputStream zis = new ZipInputStream(zipOmni.getFileInputStream());

    ZipEntry entry = null;
    try {
        while ((entry = zis.getNextEntry()) != null) {

            if (entry.isDirectory()) {

                OmniFile dir = new OmniFile(volumeId, entry.getName());
                if (dir.mkdir()) {

                    directories.add(dir);
                    if (DEBUG)
                        LogUtil.log(LogUtil.LogType.OMNI_ZIP, "dir created: " + dir.getPath());
                }
            } else {

                String path = rootFolderPath + "/" + entry.getName();
                OmniFile file = new OmniFile(volumeId, path);
                // Create any necessary directories
                file.getParentFile().mkdirs();

                if (file.exists()) {
                    file = OmniUtil.makeUniqueName(file);
                }
                OutputStream out = file.getOutputStream();

                OmniFiles.copyFileLeaveInOpen(zis, out);
                if (DEBUG)
                    LogUtil.log(LogUtil.LogType.OMNI_ZIP, "file created: " + file.getPath());

                if (added != null)
                    added.add(file.getFileObject(httpIpPort));
            }
        }
        zis.close();

        if (added != null) {

            /**
             * Iterate over the list of directories created and
             * create object files for each.
             * The full tree is now expanded such that the dir=1/0
             * can be set accurately.
             */
            for (OmniFile dir : directories)
                added.add(dir.getFileObject(httpIpPort));
        }

    } catch (IOException e) {
        LogUtil.logException(LogUtil.LogType.OMNI_ZIP, e);
        return false;
    }

    return true;
}

From source file:com.wavemaker.StudioInstallService.java

public static File unzipFile(File zipfile) {
    int BUFFER = 2048;

    String zipname = zipfile.getName();
    int extindex = zipname.lastIndexOf(".");

    try {/*from  w  w w  . j  a v a  2  s.c om*/
        File zipFolder = new File(zipfile.getParentFile(), zipname.substring(0, extindex));
        if (zipFolder.exists())
            org.apache.commons.io.FileUtils.deleteDirectory(zipFolder);
        zipFolder.mkdir();

        File currentDir = zipFolder;
        //File currentDir = zipfile.getParentFile();

        BufferedOutputStream dest = null;
        FileInputStream fis = new FileInputStream(zipfile.toString());
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            System.out.println("Extracting: " + entry);
            if (entry.isDirectory()) {
                File f = new File(currentDir, entry.getName());
                if (f.exists())
                    f.delete(); // relevant if this is the top level folder
                f.mkdir();
            } else {
                int count;
                byte data[] = new byte[BUFFER];
                //needed for non-dir file ace/ace.js created by 7zip
                File destFile = new File(currentDir, entry.getName());
                // write the files to the disk
                FileOutputStream fos = new FileOutputStream(currentDir.toString() + "/" + entry.getName());
                dest = new BufferedOutputStream(fos, BUFFER);
                while ((count = zis.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
            }
        }
        zis.close();

        return currentDir;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return (File) null;

}

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  v  a  2 s  .c  o  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: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 {/*from  w w w.  ja v  a2  s .c o  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:ClassFileUtilities.java

private static void collectJars(File dir, Map jars, Map classFiles) throws IOException {
    File[] files = dir.listFiles();
    for (int i = 0; i < files.length; i++) {
        String n = files[i].getName();
        if (n.endsWith(".jar") && files[i].isFile()) {
            Jar j = new Jar();
            j.name = files[i].getPath();
            j.file = files[i];//from  w  w w. j av a 2s  .c  o m
            j.jarFile = new JarFile(files[i]);
            jars.put(j.name, j);

            Enumeration entries = j.jarFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry ze = (ZipEntry) entries.nextElement();
                String name = ze.getName();
                if (name.endsWith(".class")) {
                    ClassFile cf = new ClassFile();
                    cf.name = name;
                    cf.jar = j;
                    classFiles.put(j.name + '!' + cf.name, cf);
                    j.files.add(cf);
                }
            }
        } else if (files[i].isDirectory()) {
            collectJars(files[i], jars, classFiles);
        }
    }
}

From source file:com.vividsolutions.jump.io.CompressedFile.java

/**
 * Searches through the .zip file looking for a file with the given extension.
 * Returns null if it doesn't find one.//from w  w  w .  j av  a 2s  . c o m
 * 
 * @deprecated only used by very old data readers which only deliver the first file in zip file [ede 05.2012]
 */
public static String getInternalZipFnameByExtension(String extension, String compressedFile) throws Exception {
    // zip file
    String inside_zip_extension;
    InputStream IS_low = new FileInputStream(compressedFile);
    ZipInputStream fr_high = new ZipInputStream(IS_low);

    // need to find the correct file within the .zip file
    ZipEntry entry;

    entry = fr_high.getNextEntry();

    while (entry != null) {
        inside_zip_extension = entry.getName().substring(entry.getName().length() - extension.length());

        if (inside_zip_extension.compareToIgnoreCase(extension) == 0) {
            return (entry.getName());
        }

        entry = fr_high.getNextEntry();
    }

    return null;
}

From source file:com.cip.crane.agent.utils.FileExtractUtils.java

/**
 * Unzip an input file into an output file.
 * <p>//from w w  w  .  j  a va2 s. c om
 * The output file is created in the output folder, having the same name
 * as the input file, minus the '.zip' extension. 
 * 
 * @param inputFile     the input .zip file
 * @param outputDir     the output directory file. 
 * @throws IOException 
 * @throws FileNotFoundException
 *  
 * @return  The {@File} with the ungzipped content.
 */
public static void unZip(final File inputFile, final File outputDir) throws FileNotFoundException, IOException {
    LOG.debug(
            String.format("Unzipping %s to dir %s.", inputFile.getAbsolutePath(), outputDir.getAbsolutePath()));

    byte[] buf = new byte[1024];
    ZipInputStream zipinputstream = null;
    ZipEntry zipentry;
    zipinputstream = new ZipInputStream(new FileInputStream(inputFile));

    zipentry = zipinputstream.getNextEntry();
    while (zipentry != null) {
        //for each entry to be extracted
        String entryName = outputDir + "/" + zipentry.getName();
        entryName = entryName.replace('/', File.separatorChar);
        entryName = entryName.replace('\\', File.separatorChar);
        int n;
        FileOutputStream fileoutputstream;
        File newFile = new File(entryName);

        if (zipentry.isDirectory()) {
            if (!newFile.mkdirs()) {
                break;
            }
            zipentry = zipinputstream.getNextEntry();
            continue;
        }
        fileoutputstream = new FileOutputStream(entryName);

        while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
            fileoutputstream.write(buf, 0, n);
        }

        fileoutputstream.close();
        zipinputstream.closeEntry();
        zipentry = zipinputstream.getNextEntry();

    } //while
    zipinputstream.close();
}

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  www. j a  v  a 2 s.co 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:com.glaf.core.entity.mybatis.MyBatisSessionFactory.java

public static Map<String, byte[]> getZipBytesMap(ZipInputStream zipInputStream) {
    Map<String, byte[]> zipMap = new java.util.HashMap<String, byte[]>();
    java.util.zip.ZipEntry zipEntry = null;
    ByteArrayOutputStream baos = null;
    BufferedOutputStream bos = null;
    byte tmpByte[] = null;
    try {/*from   w w w.ja v  a 2s. c  o  m*/
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            String name = zipEntry.getName();
            if (StringUtils.endsWith(name, "Mapper.xml")) {
                tmpByte = new byte[BUFFER];
                baos = new ByteArrayOutputStream();
                bos = new BufferedOutputStream(baos, BUFFER);
                int i = 0;
                while ((i = zipInputStream.read(tmpByte, 0, BUFFER)) != -1) {
                    bos.write(tmpByte, 0, i);
                }
                bos.flush();
                byte[] bytes = baos.toByteArray();
                IOUtils.closeStream(baos);
                IOUtils.closeStream(baos);
                zipMap.put(zipEntry.getName(), bytes);
            }
        }
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeStream(baos);
        IOUtils.closeStream(baos);
    }
    return zipMap;
}

From source file:Main.java

private static File unzip(Context context, InputStream in) throws IOException {
    File tmpDb = null;/*from  ww w. j a v a2 s  . co  m*/
    int dbFiles = 0;
    try {
        tmpDb = File.createTempFile("import", ".db");

        ZipInputStream zin = new ZipInputStream(in);
        ZipEntry sourceEntry;
        while (true) {

            sourceEntry = zin.getNextEntry();

            if (sourceEntry == null) {
                break;
            }

            if (sourceEntry.isDirectory()) {
                zin.closeEntry();
                continue;
            }

            FileOutputStream fOut;
            if (sourceEntry.getName().endsWith(".db")) {
                // Write database to tmp file
                fOut = new FileOutputStream(tmpDb);
                dbFiles++;
            } else {
                // Write all other files(images) to files dir in apps data
                int start = sourceEntry.getName().lastIndexOf("/") + 1;
                String name = sourceEntry.getName().substring(start);
                fOut = context.openFileOutput(name, Context.MODE_PRIVATE);
            }

            final OutputStream targetStream = fOut;
            try {
                int read;
                while (true) {
                    byte[] buffer = new byte[1024];
                    read = zin.read(buffer);
                    if (read == -1) {
                        break;
                    }
                    targetStream.write(buffer, 0, read);
                }
                targetStream.flush();
            } finally {
                safeCloseClosable(targetStream);
            }
            zin.closeEntry();
        }
    } finally {
        safeCloseClosable(in);
    }
    if (dbFiles != 1) {
        throw new IllegalStateException("Input file is not a valid backup");
    }
    return tmpDb;
}