Example usage for java.util.zip ZipInputStream read

List of usage examples for java.util.zip ZipInputStream read

Introduction

In this page you can find the example usage for java.util.zip ZipInputStream read.

Prototype

public int read(byte[] b, int off, int len) throws IOException 

Source Link

Document

Reads from the current ZIP entry into an array of bytes.

Usage

From source file:org.apache.asterix.event.service.AsterixEventServiceUtil.java

public static void unzip(String sourceFile, String destDir) throws IOException {
    final FileInputStream fis = new FileInputStream(sourceFile);
    final ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
    final File destDirFile = new File(destDir);
    final byte[] data = new byte[BUFFER_SIZE];

    ZipEntry entry;/*from w  ww  .  j  a  v a 2s.  c om*/
    Set<String> visitedDirs = new HashSet<>();
    createDir(destDir);
    while ((entry = zis.getNextEntry()) != null) {
        createDir(destDirFile, entry, visitedDirs);
        if (entry.isDirectory()) {
            continue;
        }
        int count;

        // write the file to the disk
        File dst = new File(destDir, entry.getName());
        FileOutputStream fos = new FileOutputStream(dst);
        BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE);
        while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
            dest.write(data, 0, count);
        }
        // close the output streams
        dest.flush();
        dest.close();
    }

    zis.close();
}

From source file:net.ftb.minecraft.MCInstaller.java

public static void launchMinecraft(String installDir, ModPack pack, LoginResponse resp, boolean isLegacy) {
    try {/*ww w  .ja  v  a 2s .co m*/
        File packDir = new File(installDir, pack.getDir());
        String gameFolder = installDir + File.separator + pack.getDir() + File.separator + "minecraft";
        File gameDir = new File(packDir, "minecraft");
        File assetDir = new File(installDir, "assets");
        File libDir = new File(installDir, "libraries");
        File natDir = new File(packDir, "natives");
        final String packVer = Settings.getSettings().getPackVer(pack.getDir());

        Logger.logInfo("Setting up native libraries for " + pack.getName() + " v " + packVer + " MC "
                + pack.getMcVersion(packVer));
        if (!gameDir.exists())
            gameDir.mkdirs();

        if (natDir.exists()) {
            natDir.delete();
        }
        natDir.mkdirs();
        if (isLegacy)
            extractLegacy();
        Version base = JsonFactory.loadVersion(new File(installDir,
                "versions/{MC_VER}/{MC_VER}.json".replace("{MC_VER}", pack.getMcVersion(packVer))));
        byte[] buf = new byte[1024];
        for (Library lib : base.getLibraries()) {
            if (lib.natives != null) {
                File local = new File(libDir, lib.getPathNatives());
                ZipInputStream input = null;
                try {
                    input = new ZipInputStream(new FileInputStream(local));
                    ZipEntry entry = input.getNextEntry();
                    while (entry != null) {
                        String name = entry.getName();
                        int n;
                        if (lib.extract == null || !lib.extract.exclude(name)) {
                            File output = new File(natDir, name);
                            output.getParentFile().mkdirs();
                            FileOutputStream out = new FileOutputStream(output);
                            while ((n = input.read(buf, 0, 1024)) > -1) {
                                out.write(buf, 0, n);
                            }
                            out.close();
                        }
                        input.closeEntry();
                        entry = input.getNextEntry();
                    }
                } catch (Exception e) {
                    ErrorUtils.tossError("Error extracting native libraries");
                    Logger.logError("", e);
                } finally {
                    try {
                        input.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
        List<File> classpath = new ArrayList<File>();
        Version packjson = new Version();
        if (!pack.getDir().equals("mojang_vanilla")) {
            if (isLegacy) {
                extractLegacyJson(new File(gameDir, "pack.json"));
            }
            if (new File(gameDir, "pack.json").exists()) {
                packjson = JsonFactory.loadVersion(new File(gameDir, "pack.json"));
                for (Library lib : packjson.getLibraries()) {
                    //Logger.logError(new File(libDir, lib.getPath()).getAbsolutePath());
                    classpath.add(new File(libDir, lib.getPath()));
                }
            }
        } else {
            packjson = base;
        }
        if (!isLegacy) //we copy the jar to a new location for legacy
            classpath.add(new File(installDir,
                    "versions/{MC_VER}/{MC_VER}.jar".replace("{MC_VER}", pack.getMcVersion(packVer))));
        else {
            FileUtils
                    .copyFile(
                            new File(installDir,
                                    "versions/{MC_VER}/{MC_VER}.jar".replace("{MC_VER}",
                                            pack.getMcVersion(packVer))),
                            new File(gameDir, "bin/" + Locations.OLDMCJARNAME));
            FileUtils.killMetaInf();
        }
        for (Library lib : base.getLibraries()) {
            classpath.add(new File(libDir, lib.getPath()));
        }

        Process minecraftProcess = MCLauncher.launchMinecraft(Settings.getSettings().getJavaPath(), gameFolder,
                assetDir, natDir, classpath, packjson.mainClass != null ? packjson.mainClass : base.mainClass,
                packjson.minecraftArguments != null ? packjson.minecraftArguments : base.minecraftArguments,
                packjson.assets != null ? packjson.assets : base.getAssets(),
                Settings.getSettings().getRamMax(), pack.getMaxPermSize(), pack.getMcVersion(packVer),
                resp.getAuth(), isLegacy);
        LaunchFrame.MCRunning = true;
        if (LaunchFrame.con != null)
            LaunchFrame.con.minecraftStarted();
        StreamLogger.prepare(minecraftProcess.getInputStream(), new LogEntry().level(LogLevel.UNKNOWN));
        String[] ignore = { "Session ID is token" };
        StreamLogger.setIgnore(ignore);
        StreamLogger.doStart();
        TrackerUtils.sendPageView(ModPack.getSelectedPack().getName() + " Launched",
                ModPack.getSelectedPack().getName());
        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
        }
        try {
            minecraftProcess.exitValue();
        } catch (IllegalThreadStateException e) {
            LaunchFrame.getInstance().setVisible(false);
            LaunchFrame.setProcMonitor(ProcessMonitor.create(minecraftProcess, new Runnable() {
                @Override
                public void run() {
                    if (!Settings.getSettings().getKeepLauncherOpen()) {
                        System.exit(0);
                    } else {
                        if (LaunchFrame.con != null)
                            LaunchFrame.con.minecraftStopped();
                        LaunchFrame launchFrame = LaunchFrame.getInstance();
                        launchFrame.setVisible(true);
                        LaunchFrame.getInstance().getEventBus().post(new EnableObjectsEvent());
                        try {
                            Settings.getSettings()
                                    .load(new FileInputStream(Settings.getSettings().getConfigFile()));
                            LaunchFrame.getInstance().tabbedPane.remove(1);
                            LaunchFrame.getInstance().optionsPane = new OptionsPane(Settings.getSettings());
                            LaunchFrame.getInstance().tabbedPane.add(LaunchFrame.getInstance().optionsPane, 1);
                            LaunchFrame.getInstance().tabbedPane.setIconAt(1, LauncherStyle.getCurrentStyle()
                                    .filterHeaderIcon(this.getClass().getResource("/image/tabs/options.png")));
                        } catch (Exception e1) {
                            Logger.logError("Failed to reload settings after launcher closed", e1);
                        }
                    }
                    LaunchFrame.MCRunning = false;
                }
            }));
        }
    } catch (Exception e) {
        Logger.logError("Error while running launchMinecraft()", e);
    }
}

From source file:org.eclipse.rtp.configurator.service.provider.internal.deploy.RepositoryManager.java

private void saveFileData(ZipInputStream zis, BufferedOutputStream bfos) throws IOException {
    int resultLength;
    byte[] data = new byte[FILE_BUFFER];
    while ((resultLength = zis.read(data, 0, FILE_BUFFER)) != -1) {
        bfos.write(data, 0, resultLength);
    }//from w w  w . ja va  2 s.com
    bfos.flush();
    bfos.close();
}

From source file:com.jcalvopinam.core.Unzipping.java

private static void joinAndUnzipFile(File inputFile, CustomFile customFile) throws IOException {

    ZipInputStream is = null;
    File path = inputFile.getParentFile();

    List<InputStream> fileInputStream = new ArrayList<>();
    for (String fileName : path.list()) {
        if (fileName.startsWith(customFile.getFileName()) && fileName.endsWith(Extensions.ZIP.getExtension())) {
            fileInputStream.add(new FileInputStream(String.format("%s%s", customFile.getPath(), fileName)));
            System.out.println(String.format("File found: %s", fileName));
        }/*  w ww. j a  va2s  .  co m*/
    }

    if (fileInputStream.size() > 0) {
        String fileNameOutput = String.format("%s%s", customFile.getPath(), customFile.getFileName());
        OutputStream os = new BufferedOutputStream(new FileOutputStream(fileNameOutput));
        try {
            System.out.println("Please wait while the files are joined: ");

            ZipEntry ze;
            for (InputStream inputStream : fileInputStream) {
                is = new ZipInputStream(inputStream);
                ze = is.getNextEntry();
                customFile.setFileName(String.format("%s_%s", REBUILT, ze.getName()));

                byte[] buffer = new byte[CustomFile.BYTE_SIZE];

                for (int readBytes; (readBytes = is.read(buffer, 0, CustomFile.BYTE_SIZE)) > -1;) {
                    os.write(buffer, 0, readBytes);
                    System.out.print(".");
                }
            }
        } finally {
            os.flush();
            os.close();
            is.close();
            renameFinalFile(customFile, fileNameOutput);
        }
    } else {
        throw new FileNotFoundException("Error: The file not exist!");
    }
    System.out.println("\nEnded process!");
}

From source file:com.aurel.track.admin.customize.category.report.ReportBL.java

/**
 * Save the new template at given location(repository, project)
 * @param repository/*from  w  w  w  . ja v  a  2 s. co  m*/
 * @param personID
 * @param project
 * @param templateName
 * @param uploadZip
 * @return an error meassage if exist
 */
public static void saveTemplate(Integer id, ZipInputStream zis) throws IOException {
    // specify buffer size for extraction
    final int BUFFER = 2048;
    // Open Zip file for reading
    File unzipDestinationDirectory = getDirTemplate(id);
    BufferedOutputStream dest = null;
    ZipEntry entry;
    while ((entry = zis.getNextEntry()) != null) {
        File destFile = new File(unzipDestinationDirectory, entry.getName());
        if (destFile.exists()) {
            destFile.delete();
        }
        // grab file's parent directory structure
        File destinationParent = destFile.getParentFile();
        // create the parent directory structure if needed
        destinationParent.mkdirs();
        int count;
        byte data[] = new byte[BUFFER];
        // write the files to the disk
        FileOutputStream fos = new FileOutputStream(destFile);
        dest = new BufferedOutputStream(fos, BUFFER);
        while ((count = zis.read(data, 0, BUFFER)) != -1) {
            dest.write(data, 0, count);
        }
        dest.flush();
        dest.close();
    }
    zis.close();
}

From source file:com.glaf.core.util.ZipUtils.java

public static Map<String, byte[]> getZipBytesMap(ZipInputStream zipInputStream, List<String> includes) {
    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 www  .j  a  v  a 2  s.c  o m
        while ((zipEntry = zipInputStream.getNextEntry()) != null) {
            String name = zipEntry.getName();
            String ext = FileUtils.getFileExt(name);
            if (includes.contains(ext) || includes.contains(ext.toLowerCase())) {
                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:org.digitalcampus.oppia.utils.FileUtils.java

public static boolean unzipFiles(String srcDirectory, String srcFile, String destDirectory) {
    try {//from   ww w.j  a va 2s. co  m
        // first make sure that all the arguments are valid and not null
        if (srcDirectory == null) {
            return false;
        }
        if (srcFile == null) {
            return false;
        }
        if (destDirectory == null) {
            return false;
        }
        if (srcDirectory.equals("")) {
            return false;
        }
        if (srcFile.equals("")) {
            return false;
        }
        if (destDirectory.equals("")) {
            return false;
        }
        // now make sure that these directories exist
        File sourceDirectory = new File(srcDirectory);
        File sourceFile = new File(srcDirectory + File.separator + srcFile);
        File destinationDirectory = new File(destDirectory);

        if (!sourceDirectory.exists()) {
            return false;
        }
        if (!sourceFile.exists()) {
            return false;
        }
        if (!destinationDirectory.exists()) {
            return false;
        }

        // now start with unzip process
        BufferedOutputStream dest = null;

        FileInputStream fis = new FileInputStream(sourceFile);
        ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));

        ZipEntry entry = null;

        while ((entry = zis.getNextEntry()) != null) {
            String outputFilename = destDirectory + File.separator + entry.getName();

            createDirIfNeeded(destDirectory, entry);

            int count;

            byte data[] = new byte[BUFFER_SIZE];

            File f = new File(outputFilename);

            // write the file to the disk
            if (!f.isDirectory()) {
                FileOutputStream fos = new FileOutputStream(f);
                dest = new BufferedOutputStream(fos, BUFFER_SIZE);

                // this counter is a hack to prevent getting stuck when
                // installing corrupted or not fully downloaded course
                // packages
                // it will prevent any course being installed with files
                // larger than around 500kb
                int counter = 0;
                while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
                    dest.write(data, 0, count);
                    counter++;
                    if (counter > 5000) {
                        dest.flush();
                        dest.close();
                        return false;
                    }
                }

                // close the output streams
                dest.flush();
                dest.close();
            }
        }

        // we are done with all the files
        // close the zip file
        zis.close();

    } catch (Exception e) {
        if (!MobileLearning.DEVELOPER_MODE) {
            BugSenseHandler.sendException(e);
        } else {
            e.printStackTrace();
        }
        return false;
    }

    return true;
}

From source file:org.ow2.clif.jenkins.jobs.Zip.java

void writeCurrentFile(ZipInputStream zip, byte[] buf, File dest) throws IOException {
    if (logger.isLoggable(Level.FINE)) {
        logger.fine("writing " + dest.getAbsolutePath());
    }//from  w  w  w . j a  v  a 2 s.  c  o  m
    int n;
    OutputStream fos = new BufferedOutputStream(new FileOutputStream(dest));
    try {
        while ((n = zip.read(buf, 0, buf.length)) > -1) {
            fos.write(buf, 0, n);
        }
    } finally {
        fos.close();
    }
}

From source file:co.cask.hydrator.transforms.CSVParser2.java

private byte[] unzip(byte[] body) throws IOException {
    Inflater inf = new Inflater();
    ByteArrayInputStream bytein = new ByteArrayInputStream(body);
    ZipInputStream gzin = new ZipInputStream(bytein);
    ByteArrayOutputStream byteout = new ByteArrayOutputStream();

    int res = 0;/*from   w ww .  jav a2 s  .com*/
    byte buf[] = new byte[1024];
    while (res >= 0) {
        res = gzin.read(buf, 0, buf.length);
        if (res > 0) {
            byteout.write(buf, 0, res);
        }
    }
    byte uncompressed[] = byteout.toByteArray();
    return uncompressed;
}

From source file:org.wso2.carbon.automation.engine.frameworkutils.ArchiveExtractorUtil.java

public static void extractFile(String sourceFilePath, String extractedDir) throws Exception {
    FileOutputStream fileoutputstream = null;
    String fileDestination = extractedDir + File.separator;
    byte[] buf = new byte[1024];
    ZipInputStream zipinputstream = null;
    ZipEntry zipentry;//from  w  w w  . j  a v a2  s  .com
    try {
        zipinputstream = new ZipInputStream(new FileInputStream(sourceFilePath));
        zipentry = zipinputstream.getNextEntry();
        while (zipentry != null) {
            //for each entry to be extracted
            String entryName = fileDestination + zipentry.getName();
            entryName = entryName.replace('/', File.separatorChar);
            entryName = entryName.replace('\\', File.separatorChar);
            int n;
            File newFile = new File(entryName);
            if (zipentry.isDirectory()) {
                if (!newFile.exists()) {
                    if (!newFile.mkdirs()) {
                        throw new Exception("Error occurred created new directory");
                    }
                }
                zipentry = zipinputstream.getNextEntry();
                continue;
            } else {
                File resourceFile = new File(entryName.substring(0, entryName.lastIndexOf(File.separator)));
                if (!resourceFile.exists()) {
                    if (!resourceFile.mkdirs()) {
                        break;
                    }
                }
            }
            fileoutputstream = new FileOutputStream(entryName);
            while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
                fileoutputstream.write(buf, 0, n);
            }
            fileoutputstream.close();
            zipinputstream.closeEntry();
            zipentry = zipinputstream.getNextEntry();
        }
        zipinputstream.close();
    } catch (IOException e) {
        log.error("Error on archive extraction ", e);
        throw new IOException("Error on archive extraction ", e);
    } finally {
        if (fileoutputstream != null) {
            fileoutputstream.close();
        }
        if (zipinputstream != null) {
            zipinputstream.close();
        }
    }
}