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:autohit.common.Utils.java

/**
 *  Copy files.  I can't believe I have to write this.  It will always
 *  overwrite an existing file.//from  ww  w  . java 2 s.  c  o m
 * @param source source file path
 * @param dest destination file path
 * @return string containing errors or messages
 */
public static String copy(String source, String dest) {

    String overwrite = " ";

    BufferedOutputStream bos = null;
    try {

        File destf = new File(dest);
        if (destf.exists()) {
            destf.delete();
            overwrite = " [overwrite] ";
        }

        byte[] buf = new byte[1024];
        int sbuf;

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(source));
        bos = new BufferedOutputStream(new FileOutputStream(dest));

        sbuf = bis.read(buf, 0, 1024);
        while (sbuf > 0) {
            bos.write(buf, 0, sbuf);
            sbuf = bis.read(buf, 0, 1024);
        }
    } catch (Exception e) {
    }
    try {
        bos.close();
    } catch (Exception e) {
        return "Copy failed for=" + source + Constants.CRUDE_SEPERATOR;
    }
    return "Copied file=" + source + overwrite + Constants.CRUDE_SEPERATOR;
}

From source file:de.lazyzero.kkMulticopterFlashTool.utils.Zip.java

public static void unzip2folder(File zipFile, File toFolder) throws FileExistsException {
    if (!toFolder.exists()) {
        toFolder.mkdirs();/* www .  j  a v a2 s . c o  m*/
    } else if (toFolder.isFile()) {
        throw new FileExistsException(toFolder.getName());
    }

    try {
        ZipEntry entry;
        @SuppressWarnings("resource")
        ZipFile zipfile = new ZipFile(zipFile);
        Enumeration<? extends ZipEntry> e = zipfile.entries();
        while (e.hasMoreElements()) {
            entry = e.nextElement();

            //            String newDir;
            //            if (entry.getName().indexOf("/") == -1) {
            //               newDir = zipFile.getName().substring(0, zipFile.getName().indexOf("."));
            //            } else {
            //               newDir = entry.getName().substring(0, entry.getName().indexOf("/"));
            //            }
            //            String folder = toFolder + (File.separatorChar+"") + newDir;
            //            System.out.println(folder);
            //            if ((new File(folder).mkdir())) {
            //               System.out.println("Done.");
            //            }
            System.out.println("Extracting: " + entry);
            if (entry.isDirectory()) {
                new File(toFolder + (File.separatorChar + "") + entry.getName()).mkdir();
            } else {
                BufferedInputStream is = new BufferedInputStream(zipfile.getInputStream(entry));
                int count;
                byte data[] = new byte[2048];
                String fileName = toFolder + (File.separatorChar + "") + entry.getName();
                FileOutputStream fos = new FileOutputStream(fileName);
                BufferedOutputStream dest = new BufferedOutputStream(fos, 2048);
                while ((count = is.read(data, 0, 2048)) != -1) {
                    dest.write(data, 0, count);
                }
                dest.flush();
                dest.close();
                is.close();
                System.out.println("extracted to: " + fileName);
            }

        }
    } catch (ZipException e1) {
        zipFile.delete();
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } finally {

    }

}

From source file:Main.java

public static void unzip(String strZipFile) {

    try {//from w w  w.  j  a va  2 s . c o  m
        /*
         * STEP 1 : Create directory with the name of the zip file
         * 
         * For e.g. if we are going to extract c:/demo.zip create c:/demo directory where we can extract all the zip entries
         */
        File fSourceZip = new File(strZipFile);
        String zipPath = strZipFile.substring(0, strZipFile.length() - 4);
        File temp = new File(zipPath);
        temp.mkdir();
        System.out.println(zipPath + " created");

        /*
         * STEP 2 : Extract entries while creating required sub-directories
         */
        ZipFile zipFile = new ZipFile(fSourceZip);
        Enumeration<? extends ZipEntry> e = zipFile.entries();

        while (e.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) e.nextElement();
            File destinationFilePath = new File(zipPath, entry.getName());

            // create directories if required.
            destinationFilePath.getParentFile().mkdirs();

            // if the entry is directory, leave it. Otherwise extract it.
            if (entry.isDirectory()) {
                continue;
            } else {
                // System.out.println("Extracting " + destinationFilePath);

                /*
                 * Get the InputStream for current entry of the zip file using
                 * 
                 * InputStream getInputStream(Entry entry) method.
                 */
                BufferedInputStream bis = new BufferedInputStream(zipFile.getInputStream(entry));

                int b;
                byte buffer[] = new byte[1024];

                /*
                 * read the current entry from the zip file, extract it and write the extracted file.
                 */
                FileOutputStream fos = new FileOutputStream(destinationFilePath);
                BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);

                while ((b = bis.read(buffer, 0, 1024)) != -1) {
                    bos.write(buffer, 0, b);
                }

                // flush the output stream and close it.
                bos.flush();
                bos.close();

                // close the input stream.
                bis.close();
            }

        }
        zipFile.close();
    } catch (IOException ioe) {
        System.out.println("IOError :" + ioe);
    }

}

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

private static byte[] computePayloadSHA256Hash(byte[] payload) throws NoSuchAlgorithmException, IOException {
    BufferedInputStream inputStream = new BufferedInputStream(new ByteArrayInputStream(payload));
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] buffer = new byte[4096];
    int bytesRead;
    while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) != -1) {
        messageDigest.update(buffer, 0, bytesRead);
    }// www.j a v  a 2  s  . com
    return messageDigest.digest();
}

From source file:com.linkedin.pinot.core.startree.StarTreeSerDe.java

/**
 * Utility method to StarTree version./*w  w  w  .  ja  va  2s.  c  om*/
 * Presence of {@ref #MAGIC_MARKER} indicates on-heap format, while its
 * absence indicates on-heap format.
 *
 * @param bufferedInputStream
 * @return
 * @throws IOException
 */
public static StarTreeFormatVersion getStarTreeVersion(BufferedInputStream bufferedInputStream)
        throws IOException {
    byte[] magicBytes = new byte[MAGIC_MARKER_SIZE_IN_BYTES];

    bufferedInputStream.mark(MAGIC_MARKER_SIZE_IN_BYTES);
    bufferedInputStream.read(magicBytes, 0, MAGIC_MARKER_SIZE_IN_BYTES);
    bufferedInputStream.reset();

    LBufferAPI lBuffer = new LBuffer(MAGIC_MARKER_SIZE_IN_BYTES);
    lBuffer.readFrom(magicBytes, 0);
    long magicMarker = lBuffer.getLong(0);

    if (magicMarker == MAGIC_MARKER) {
        return StarTreeFormatVersion.OFF_HEAP;
    } else {
        return StarTreeFormatVersion.ON_HEAP;
    }
}

From source file:com.nwn.NwnFileHandler.java

/**
 * Downloads file from given url//from w w  w  .j a v a 2  s .  com
 * @param fileUrl String of url to download
 * @param dest Location on system where file should be downloaded
 * @return True if download success, False if download failed
 */
public static boolean downloadFile(String fileUrl, String dest) {
    try {
        URL url = new URL(fileUrl);
        BufferedInputStream bis = new BufferedInputStream(url.openStream());
        FileOutputStream fis = new FileOutputStream(dest);
        String fileSizeString = url.openConnection().getHeaderField("Content-Length");
        double fileSize = Double.parseDouble(fileSizeString);
        byte[] buffer = new byte[1024];
        int count;
        double bytesDownloaded = 0.0;
        while ((count = bis.read(buffer, 0, 1024)) != -1) {
            bytesDownloaded += count;
            fis.write(buffer, 0, count);

            int downloadStatus = (int) ((bytesDownloaded / fileSize) * 100);

            System.out.println("Downloading " + fileUrl + " to " + dest + " " + downloadStatus + "%");
        }
        fis.close();
        bis.close();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
        return false;
    } catch (FileNotFoundException ex) {
        ex.printStackTrace();
        return false;
    } catch (IOException ex) {
        ex.printStackTrace();
        return false;
    }

    return true;
}

From source file:Main.java

public static void unzip(URL _url, URL _dest, boolean _remove_top) {
    int BUFFER_SZ = 2048;
    File file = new File(_url.getPath());

    String dest = _dest.getPath();
    new File(dest).mkdir();

    try {/* w w  w  .j a v  a2s  . c  om*/
        ZipFile zip = new ZipFile(file);
        Enumeration<? extends ZipEntry> zipFileEntries = zip.entries();

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

            if (_remove_top)
                currentEntry = currentEntry.substring(currentEntry.indexOf('/'), currentEntry.length());

            File destFile = new File(dest, currentEntry);
            //destFile = new File(newPath, destFile.getName());
            File destinationParent = destFile.getParentFile();

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

            if (!entry.isDirectory()) {
                BufferedInputStream is;
                is = new BufferedInputStream(zip.getInputStream(entry));
                int currentByte;
                // establish buffer for writing file
                byte data[] = new byte[BUFFER_SZ];

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

                // read and write until last byte is encountered
                while ((currentByte = is.read(data, 0, BUFFER_SZ)) != -1) {
                    dst.write(data, 0, currentByte);
                }
                dst.flush();
                dst.close();
                is.close();
            }
            /*
            if (currentEntry.endsWith(".zip"))
            {
            // found a zip file, try to open
            extractFolder(destFile.getAbsolutePath());
            }*/
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:Main.java

private static void zipFile(ZipOutputStream zipOutputStream, String sourcePath) throws IOException {

    java.io.File files = new java.io.File(sourcePath);
    java.io.File[] fileList = files.listFiles();

    String entryPath = "";
    BufferedInputStream input = null;
    for (java.io.File file : fileList) {
        if (file.isDirectory()) {
            zipFile(zipOutputStream, file.getPath());
        } else {//  w w w .j av a  2  s  . c o  m
            byte data[] = new byte[BUFFER_SIZE];
            FileInputStream fileInputStream = new FileInputStream(file.getPath());
            input = new BufferedInputStream(fileInputStream, BUFFER_SIZE);
            entryPath = file.getAbsolutePath().replace(parentPath, "");

            ZipEntry entry = new ZipEntry(entryPath);
            zipOutputStream.putNextEntry(entry);

            int count;
            while ((count = input.read(data, 0, BUFFER_SIZE)) != -1) {
                zipOutputStream.write(data, 0, count);
            }
            input.close();
        }
    }

}

From source file:com.pieframework.runtime.utils.Zipper.java

public static void unzip(String zipFile, String toDir) throws ZipException, IOException {

    int BUFFER = 2048;
    File file = new File(zipFile);

    ZipFile zip = new ZipFile(file);
    String newPath = toDir;// www  .j a  va  2 s.c o  m

    File toDirectory = new File(newPath);
    if (!toDirectory.exists()) {
        toDirectory.mkdir();
    }
    Enumeration zipFileEntries = zip.entries();

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

        String currentEntry = entry.getName();
        File destFile = new File(newPath, FilenameUtils.separatorsToSystem(currentEntry));
        //System.out.println(currentEntry);
        File destinationParent = destFile.getParentFile();

        // create the parent directory structure if needed
        destinationParent.mkdirs();
        if (!entry.isDirectory()) {
            BufferedInputStream is = new BufferedInputStream(zip.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);
            BufferedOutputStream 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);
            }
            dest.flush();
            dest.close();
            is.close();
        }
    }
    zip.close();

}

From source file:com.byraphaelmedeiros.autosubdown.AutoSubDown.java

private static void downloadTo(Rule rule, String link) {
    LOGGER.log(Level.INFO, "Downloading " + link + "...");

    try {// ww  w. java2 s  .  c o  m
        String extension = FilenameUtils.getExtension(link);
        BufferedInputStream bis = new BufferedInputStream(new URL(link).openStream());
        FileOutputStream fos = new FileOutputStream(
                rule.getDownloadTo() + File.separator + rule.getFileName() + "." + extension);
        BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);

        byte data[] = new byte[1024];
        int x = 0;

        while ((x = bis.read(data, 0, 1024)) >= 0) {
            bos.write(data, 0, x);
        }

        bos.close();
        bis.close();
    } catch (MalformedURLException e) {
        //e.printStackTrace();
        LOGGER.log(Level.WARNING, "Invalid URL! (" + link + ")");
    } catch (IOException e) {
        //e.printStackTrace();
        LOGGER.log(Level.WARNING, "Unable to access the URL (" + link + ").");
    }
}