Example usage for java.io BufferedInputStream read

List of usage examples for java.io BufferedInputStream read

Introduction

In this page you can find the example usage for java.io BufferedInputStream read.

Prototype

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

Source Link

Document

Reads bytes from this byte-input stream into the specified byte array, starting at the given offset.

Usage

From source file:Main.java

/**
 * Uncompresses zipped files//from w  w w  . j  a va2 s  .  co  m
 * @param zippedFile The file to uncompress
 * @param destinationDir Where to put the files
 * @return  list of unzipped files
 * @throws java.io.IOException thrown if there is a problem finding or writing the files
 */
public static List<File> unzip(File zippedFile, File destinationDir) throws IOException {
    int buffer = 2048;

    List<File> unzippedFiles = new ArrayList<File>();

    BufferedOutputStream dest;
    BufferedInputStream is;
    ZipEntry entry;
    ZipFile zipfile = new ZipFile(zippedFile);
    Enumeration e = zipfile.entries();
    while (e.hasMoreElements()) {
        entry = (ZipEntry) e.nextElement();

        is = new BufferedInputStream(zipfile.getInputStream(entry));
        int count;
        byte data[] = new byte[buffer];

        File destFile;

        if (destinationDir != null) {
            destFile = new File(destinationDir, entry.getName());
        } else {
            destFile = new File(entry.getName());
        }

        FileOutputStream fos = new FileOutputStream(destFile);
        dest = new BufferedOutputStream(fos, buffer);
        try {
            while ((count = is.read(data, 0, buffer)) != -1) {
                dest.write(data, 0, count);
            }

            unzippedFiles.add(destFile);
        } finally {
            dest.flush();
            dest.close();
            is.close();
        }
    }

    return unzippedFiles;
}

From source file:com.stevpet.sonar.plugins.dotnet.mscover.codecoverage.command.ZipUtils.java

/**
 * Extracts the specified folder from the specified archive, into the supplied output directory.
 * //w w  w  .  j  av a2s .co  m
 * @param archivePath
 *          the archive Path
 * @param folderToExtract
 *          the folder to extract
 * @param outputDirectory
 *          the output directory
 * @return the extracted folder path
 * @throws IOException
 *           if a problem occurs while extracting
 */
public static File extractArchiveFolderIntoDirectory(String archivePath, String folderToExtract,
        String outputDirectory) throws IOException {
    File destinationFolder = new File(outputDirectory);
    destinationFolder.mkdirs();

    ZipFile zip = null;
    try {
        zip = new ZipFile(new File(archivePath));
        Enumeration<?> zipFileEntries = zip.entries();
        // Process each entry
        while (zipFileEntries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
            String currentEntry = entry.getName();
            if (currentEntry.startsWith(folderToExtract)) {
                File destFile = new File(destinationFolder, currentEntry);
                destFile.getParentFile().mkdirs();
                if (!entry.isDirectory()) {
                    BufferedInputStream is = null;
                    BufferedOutputStream dest = null;
                    try {
                        is = new BufferedInputStream(zip.getInputStream(entry));
                        int currentByte;
                        // establish buffer for writing file
                        byte data[] = new byte[BUFFER_SIZE];

                        // write the current file to disk
                        FileOutputStream fos = new FileOutputStream(destFile);
                        dest = new BufferedOutputStream(fos, BUFFER_SIZE);

                        // read and write until last byte is encountered
                        while ((currentByte = is.read(data, 0, BUFFER_SIZE)) != -1) {
                            dest.write(data, 0, currentByte);
                        }
                    } finally {
                        if (dest != null) {
                            dest.flush();
                        }
                        IOUtils.closeQuietly(dest);
                        IOUtils.closeQuietly(is);
                    }
                }
            }
        }
    } finally {
        if (zip != null) {
            zip.close();
        }
    }

    return new File(destinationFolder, folderToExtract);
}

From source file:com.eryansky.modules.disk.utils.DiskUtils.java

/**
 * ????//from   ww  w  .  j  a v  a2s  .  c o m
 *
 * @param inFiles
 *            ?
 * @return
 * @throws Exception
 */
private static void doZipFile(ZipOutputStream zipOut, List<File> inFiles) throws Exception {
    if (Collections3.isNotEmpty(inFiles)) {
        Map<String, Integer> countMap = Maps.newHashMap();

        for (File file : inFiles) {
            String name = file.getName();
            Integer mapVal = countMap.get(name);
            String newName = name;
            if (mapVal == null) {
                mapVal = 0;
            } else {
                mapVal++;
                int index = name.lastIndexOf(".");
                if (index > -1) {
                    newName = (new StringBuffer(name).insert(index, "(" + mapVal + ")")).toString();
                } else {
                    newName = (new StringBuffer(name).append("(" + mapVal + ")")).toString();
                }
            }
            if (file.getDiskFile().isFile()) {
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file.getDiskFile()));
                ZipEntry entry = new ZipEntry(newName);
                zipOut.putNextEntry(entry);
                byte[] buff = new byte[BUFFER_SIZE_DIFAULT];
                int size;
                while ((size = bis.read(buff, 0, buff.length)) != -1) {
                    zipOut.write(buff, 0, size);
                }
                zipOut.closeEntry();
                bis.close();
            }
            countMap.put(name, mapVal);

        }
    }
}

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

public static void save(String filename, InputStream inputStream) {
    if (filename == null || inputStream == null) {
        return;//from ww  w  .  j ava  2 s .  c  o m
    }
    String path = "";
    String sp = System.getProperty("file.separator");
    if (filename.indexOf(sp) != -1) {
        path = filename.substring(0, filename.lastIndexOf(sp));
    }
    if (filename.indexOf("/") != -1) {
        path = filename.substring(0, filename.lastIndexOf("/"));
    }
    path = getJavaFileSystemPath(path);
    java.io.File dir = new java.io.File(path + sp);
    mkdirsWithExistsCheck(dir);
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        bis = new BufferedInputStream(inputStream);
        bos = new BufferedOutputStream(new FileOutputStream(filename));
        int bytesRead = 0;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((bytesRead = bis.read(buffer, 0, BUFFER_SIZE)) != -1) {
            bos.write(buffer, 0, bytesRead);
        }
        bos.flush();
        bis.close();
        bos.close();
        bis = null;
        bos = null;
    } catch (IOException ex) {
        bis = null;
        bos = null;
        throw new RuntimeException(ex);
    } finally {
        try {
            if (bis != null) {
                bis.close();
                bis = null;
            }
            if (bos != null) {
                bos.close();
                bos = null;
            }
        } catch (IOException ioe) {
        }
    }
}

From source file:eionet.gdem.utils.ZipUtil.java

/**
 * Unzips files to output directory.//from w w w.j  a v  a2s  . co  m
 * @param inZip Zip file
 * @param outDir Output directory
 * @throws IOException If an error occurs.
 */
public static void unzip(String inZip, String outDir) throws IOException {

    File sourceZipFile = new File(inZip);
    File unzipDestinationDirectory = new File(outDir);

    // Open Zip file for reading
    ZipFile zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);

    // Create an enumeration of the entries in the zip file
    Enumeration zipFileEntries = zipFile.entries();

    // Process each entry
    while (zipFileEntries.hasMoreElements()) {
        // grab a zip file entry
        ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();

        String currentEntry = entry.getName();
        // System.out.println("Extracting: " + entry);

        File destFile = new File(unzipDestinationDirectory, currentEntry);

        // grab file's parent directory structure
        File destinationParent = destFile.getParentFile();

        // create the parent directory structure if needed
        destinationParent.mkdirs();

        // extract file if not a directory
        if (!entry.isDirectory()) {
            BufferedInputStream is = null;
            BufferedOutputStream dest = null;
            try {
                is = new BufferedInputStream(zipFile.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte[] data = new byte[BUFFER];

                // write the current file to disk
                FileOutputStream fos = new FileOutputStream(destFile);
                dest = new BufferedOutputStream(fos, BUFFER);

                // read and write until last byte is encountered
                while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                    dest.write(data, 0, currentByte);
                }
            } finally {
                IOUtils.closeQuietly(dest);
                IOUtils.closeQuietly(is);
            }
        }
    }
    zipFile.close();
}

From source file:org.dasein.cloud.aws.storage.S3Method.java

static public byte[] computeMD5Hash(InputStream is) throws NoSuchAlgorithmException, IOException {
    BufferedInputStream bis = new BufferedInputStream(is);

    try {/*www .  j a v  a2 s .  c o  m*/
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[16384];
        int bytesRead = -1;
        while ((bytesRead = bis.read(buffer, 0, buffer.length)) != -1) {
            messageDigest.update(buffer, 0, bytesRead);
        }
        return messageDigest.digest();
    } finally {
        try {
            bis.close();
        } catch (Exception e) {
            System.err.println("Unable to close input stream of hash candidate: " + e);
        }
    }
}

From source file:com.elastica.helper.FileUtility.java

public static void extractJar(final String storeLocation, final Class<?> clz) throws IOException {
    File firefoxProfile = new File(storeLocation);
    String location = clz.getProtectionDomain().getCodeSource().getLocation().getFile();

    JarFile jar = new JarFile(location);
    System.out.println("Extracting jar file::: " + location);
    firefoxProfile.mkdir();/*from   w  ww .  j a  v a  2s.com*/

    Enumeration<?> jarFiles = jar.entries();
    while (jarFiles.hasMoreElements()) {
        ZipEntry entry = (ZipEntry) jarFiles.nextElement();
        String currentEntry = entry.getName();
        File destinationFile = new File(storeLocation, currentEntry);
        File destinationParent = destinationFile.getParentFile();

        // create the parent directory structure if required
        destinationParent.mkdirs();
        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(jar.getInputStream(entry));
            int currentByte;

            // buffer for writing file
            byte[] data = new byte[BUFFER];

            // write the current file to disk
            FileOutputStream fos = new FileOutputStream(destinationFile);
            BufferedOutputStream destination = new BufferedOutputStream(fos, BUFFER);

            // read and write till last byte
            while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
                destination.write(data, 0, currentByte);
            }

            destination.flush();
            destination.close();
            is.close();
        }
    }

    FileUtils.deleteDirectory(new File(storeLocation + "\\META-INF"));
    if (OSUtility.isWindows()) {
        new File(storeLocation + "\\" + clz.getCanonicalName().replaceAll("\\.", "\\\\") + ".class").delete();
    } else {
        new File(storeLocation + "/" + clz.getCanonicalName().replaceAll("\\.", "/") + ".class").delete();
    }
}

From source file:com.ibm.amc.FileManager.java

private static void compressFile(File file, ZipOutputStream out, String basedir) {
    try {/* ww  w  .j  av a2 s  .c  o  m*/
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        ZipEntry entry = new ZipEntry(basedir + file.getName());
        out.putNextEntry(entry);
        int length = Long.valueOf(file.length()).intValue();
        int buffer = ZIP_BUFFER;
        if (length != 0) {
            buffer = length;
        }
        int count;
        byte data[] = new byte[buffer];
        while ((count = bis.read(data, 0, buffer)) != -1) {
            out.write(data, 0, count);
        }
        bis.close();
    } catch (Exception e) {
        throw new AmcRuntimeException(e);
    }
}

From source file:org.openo.nfvo.jujuvnfmadapter.common.DownloadCsarManager.java

/**
 * unzip CSAR packge// ww w  .  ja  v a2s.c  o m
 * @param fileName filePath
 * @return
 */
public static int unzipCSAR(String fileName, String filePath) {
    final int BUFFER = 2048;
    int status = 0;

    try {
        ZipFile zipFile = new ZipFile(fileName);
        Enumeration emu = zipFile.entries();
        int i = 0;
        while (emu.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) emu.nextElement();
            //read directory as file first,so only need to create directory
            if (entry.isDirectory()) {
                new File(filePath + entry.getName()).mkdirs();
                continue;
            }
            BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));
            File file = new File(filePath + entry.getName());
            //Because that is random to read zipfile,maybe the file is read first
            //before the directory is read,so we need to create directory first.
            File parent = file.getParentFile();
            if (parent != null && (!parent.exists())) {
                parent.mkdirs();
            }
            FileOutputStream fos = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(fos, BUFFER);

            int count;
            byte data[] = new byte[BUFFER];
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                bos.write(data, 0, count);
            }
            bos.flush();
            bos.close();
            bis.close();

            if (entry.getName().endsWith(".zip")) {
                File subFile = new File(filePath + entry.getName());
                if (subFile.exists()) {
                    int subStatus = unzipCSAR(filePath + entry.getName(), subFile.getParent() + "/");
                    if (subStatus != 0) {
                        LOG.error("sub file unzip fail!" + subFile.getName());
                        status = Constant.UNZIP_FAIL;
                        return status;
                    }
                }
            }
        }
        status = Constant.UNZIP_SUCCESS;
        zipFile.close();
    } catch (Exception e) {
        status = Constant.UNZIP_FAIL;
        e.printStackTrace();
    }
    return status;
}

From source file:com.gs.tools.doc.extractor.core.util.HttpUtility.java

public static byte[] getFile(String sourceUrl) throws Exception {
    byte[] result = null;

    /*/*from   www . ja v a2 s . c  om*/
     * Create http parameter to set Connection timeout = 300000 Socket/Read
     * timeout = 300000 Socket Read Buffer = 10485760
     */
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 300000);
    HttpConnectionParams.setSocketBufferSize(httpParams, 10485760);
    HttpConnectionParams.setSoTimeout(httpParams, 300000);

    // set the http param to the DefaultHttpClient
    HttpClient httpClient = new DefaultHttpClient(httpParams);

    // create POST method and set the URL and POST data
    HttpGet httpGet = new HttpGet(sourceUrl);

    logger.info("Execute the GET request ...");
    // Execute the POST request on the http client to get the response
    HttpResponse response = httpClient.execute(httpGet, new BasicHttpContext());
    if (null != response && response.getStatusLine().getStatusCode() == 200) {
        HttpEntity httpEntity = response.getEntity();
        if (null != httpEntity) {

            // read the response to String
            InputStream responseStream = httpEntity.getContent();
            if (null != responseStream) {
                BufferedInputStream reader = null;
                ByteArrayOutputStream baos = null;
                try {
                    baos = new ByteArrayOutputStream();
                    reader = new BufferedInputStream(responseStream);
                    int count = 0;
                    int size = 1024 * 1024;
                    byte[] chBuff = new byte[size];
                    while ((count = reader.read(chBuff, 0, size)) >= 0) {
                        baos.write(chBuff, 0, count);
                    }
                    result = baos.toByteArray();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    throw ex;
                } finally {
                    IOUtils.closeQuietly(responseStream);
                    IOUtils.closeQuietly(reader);
                    IOUtils.closeQuietly(baos);
                }
            }
        }
    }
    logger.info("data read complete");
    return result;
}