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:org.jorge.lolin1.io.net.HTTPServices.java

public static void downloadFile(final String whatToDownload, final File whereToSaveIt) throws IOException {
    logString("debug", "Downloading url " + whatToDownload);
    AsyncTask<Void, Void, Object> imageDownloadAsyncTask = new AsyncTask<Void, Void, Object>() {
        @Override//from  w w w  .  j a  va2  s  . c om
        protected Object doInBackground(Void... params) {
            Object ret = null;
            BufferedInputStream bufferedInputStream = null;
            FileOutputStream fileOutputStream = null;
            try {
                logString("debug", "Opening stream for " + whatToDownload);
                bufferedInputStream = new BufferedInputStream(
                        new URL(URLDecoder.decode(whatToDownload, "UTF-8").replaceAll(" ", "%20"))
                                .openStream());
                logString("debug", "Opened stream for " + whatToDownload);
                fileOutputStream = new FileOutputStream(whereToSaveIt);

                final byte data[] = new byte[1024];
                int count;
                logString("debug", "Loop-writing " + whatToDownload);
                while ((count = bufferedInputStream.read(data, 0, 1024)) != -1) {
                    fileOutputStream.write(data, 0, count);
                }
                logString("debug", "Loop-written " + whatToDownload);
            } catch (IOException e) {
                return e;
            } finally {
                if (bufferedInputStream != null) {
                    try {
                        bufferedInputStream.close();
                    } catch (IOException e) {
                        ret = e;
                    }
                }
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                        ret = e;
                    }
                }
            }
            return ret;
        }
    };
    imageDownloadAsyncTask.executeOnExecutor(fileDownloadExecutor);
    Object returned = null;
    try {
        returned = imageDownloadAsyncTask.get();
    } catch (ExecutionException | InterruptedException e) {
        Crashlytics.logException(e);
    }
    if (returned != null) {
        throw (IOException) returned;
    }
}

From source file:edu.harvard.i2b2.eclipse.plugins.metadataLoader.util.FileUtil.java

public static void unZipAll(File source, File destination) throws IOException {
    System.out.println("Unzipping - " + source.getName());
    int BUFFER = 2048;

    ZipFile zip = new ZipFile(source);
    try {/* w w w .  j  a va 2s .com*/
        destination.getParentFile().mkdirs();
        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(destination, 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 = null;
                FileOutputStream fos = null;
                BufferedOutputStream dest = null;
                try {
                    is = new BufferedInputStream(zip.getInputStream(entry));
                    int currentByte;
                    // establish buffer for writing file
                    byte data[] = new byte[BUFFER];

                    // write the current file to disk
                    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);
                    }
                } catch (Exception e) {
                    System.out.println("unable to extract entry:" + entry.getName());
                    throw e;
                } finally {
                    if (dest != null) {
                        dest.close();
                    }
                    if (fos != null) {
                        fos.close();
                    }
                    if (is != null) {
                        is.close();
                    }
                }
            } else {
                //Create directory
                destFile.mkdirs();
            }

            if (currentEntry.endsWith(".zip")) {
                // found a zip file, try to extract
                unZipAll(destFile, destinationParent);
                if (!destFile.delete()) {
                    System.out.println("Could not delete zip");
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Failed to successfully unzip:" + source.getName());
    } finally {
        zip.close();
    }
    System.out.println("Done Unzipping:" + source.getName());
}

From source file:net.sf.sahi.util.Utils.java

public static byte[] getBytes(final InputStream in, final int contentLength) throws IOException {
    BufferedInputStream bin = new BufferedInputStream(in, BUFFER_SIZE);

    if (contentLength != -1) {
        int totalBytesRead = 0;
        byte[] buffer = new byte[contentLength];
        while (totalBytesRead < contentLength) {
            int bytesRead = -1;
            try {
                bytesRead = bin.read(buffer, totalBytesRead, contentLength - totalBytesRead);
            } catch (EOFException e) {
            }// w  ww .j  a va2 s .c o m
            if (bytesRead == -1) {
                break;
            }
            totalBytesRead += bytesRead;
        }
        return buffer;
    } else {
        ByteArrayOutputStream byteArOut = new ByteArrayOutputStream();
        BufferedOutputStream bout = new BufferedOutputStream(byteArOut);
        try {
            int totalBytesRead = 0;
            byte[] buffer = new byte[BUFFER_SIZE];

            while (true) {
                int bytesRead = -1;
                try {
                    bytesRead = bin.read(buffer);
                } catch (EOFException e) {
                }
                if (bytesRead == -1) {
                    break;
                }
                bout.write(buffer, 0, bytesRead);
                totalBytesRead += bytesRead;
            }
        } catch (SocketTimeoutException ste) {
            ste.printStackTrace();
        }
        bout.flush();
        bout.close();
        return byteArOut.toByteArray();
    }
}

From source file:com.headswilllol.basiclauncher.Launcher.java

public static void unzip(ZipFile zip, ZipEntry entry, File dest) { // convenience method for unzipping from archive
    if (dest.exists())
        dest.delete();/*from   w  w w.  ja v a 2s.  c o m*/
    dest.getParentFile().mkdirs();
    try {
        BufferedInputStream bIs = new BufferedInputStream(zip.getInputStream(entry));
        int b;
        byte buffer[] = new byte[1024];
        FileOutputStream fOs = new FileOutputStream(dest);
        BufferedOutputStream bOs = new BufferedOutputStream(fOs, 1024);
        while ((b = bIs.read(buffer, 0, 1024)) != -1)
            bOs.write(buffer, 0, b);
        bOs.flush();
        bOs.close();
        bIs.close();
    } catch (Exception ex) {
        ex.printStackTrace();
        createExceptionLog(ex);
        progress = "Failed to unzip " + entry.getName();
        fail = "Errors occurred; see log file for details";
        launcher.paintImmediately(0, 0, width, height);
    }
}

From source file:com.aurel.track.lucene.util.FileUtil.java

public static void unzipFile(File uploadZip, File unzipDestinationDirectory) throws IOException {
    if (!unzipDestinationDirectory.exists()) {
        unzipDestinationDirectory.mkdirs();
    }//from w ww.  j  a  v  a 2 s . c om
    final int BUFFER = 2048;
    // Open Zip file for reading
    ZipFile zipFile = new ZipFile(uploadZip, 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();
        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 = 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);
            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();
        }
    }
    zipFile.close();
}

From source file:eu.nubomedia.nubomedia_kurento_health_communicator_android.kc_and_communicator.util.FileUtils.java

public static Bitmap entityToBitmap(Context context, HttpEntity entity, final String contentId,
        boolean withProgressBar, Long contentSize) {
    try {/*from  ww w . j a  v  a2 s .co  m*/
        File file = new File(getDir(), contentId);
        file.createNewFile();
        InputStream is = entity.getContent();

        /*
         * Read bytes to the Buffer until there is nothing more to read(-1)
         * and write on the fly in the file.
         */
        final FileOutputStream fos = new FileOutputStream(file);
        final int BUFFER_SIZE = 23 * 1024;
        BufferedInputStream bis = new BufferedInputStream(is, BUFFER_SIZE);
        byte[] baf = new byte[BUFFER_SIZE];
        int actual = 0;
        long total = 0;
        int totalpercent = 0;
        int auxtotal = 0;

        while (actual != -1) {
            fos.write(baf, 0, actual);
            actual = bis.read(baf, 0, BUFFER_SIZE);

            if (withProgressBar) {
                try {
                    total = total + actual;
                    auxtotal = (int) (((total * 100) / contentSize)) / 10;
                    if ((totalpercent != auxtotal) && (totalpercent != 10)) {
                        totalpercent = auxtotal;
                        Intent intent = new Intent();
                        intent.setAction(ConstantKeys.BROADCAST_DIALOG_PROGRESSBAR);
                        intent.putExtra(ConstantKeys.TOTAL, totalpercent * 10);
                        intent.putExtra(ConstantKeys.LOCALID,
                                contentId.replace(ConstantKeys.EXTENSION_3GP, ConstantKeys.STRING_DEFAULT)
                                        .replace(ConstantKeys.EXTENSION_JPG, ConstantKeys.STRING_DEFAULT));
                        context.sendBroadcast(intent);
                    }
                } catch (Exception e) {
                    log.error("Error tryng to send broadcast to progressbar", e);
                }
            }
        }

        fos.close();

        if (contentId.contains(ConstantKeys.EXTENSION_JPG)) {
            return decodeSampledBitmapFromPath(file.getAbsolutePath(), 200, 200);
        } else {
            return ThumbnailUtils.createVideoThumbnail(file.getAbsolutePath(),
                    MediaStore.Images.Thumbnails.MINI_KIND);
        }

    } catch (Exception e) {
        new File(getDir(), contentId).delete();
        return null;
    }
}

From source file:com.dynamobi.network.DynamoNetworkUdr.java

/**
 * Fetches and stores a .jar file from a repo url/file-url, doing an md5sum check too.
 *//*  w w  w. jav a  2  s  .  c  om*/
private static void fetchJar(String url, String jarFile, String md5sum) throws SQLException {
    BufferedInputStream in = null;
    FileOutputStream out = null;
    try {
        String outfile = FarragoProperties.instance().expandProperties("${FARRAGO_HOME}/plugin/" + jarFile);
        in = new BufferedInputStream(new URL(url).openStream());
        out = new FileOutputStream(outfile);
        final int block_size = 1 << 18; // 256 kb
        byte data[] = new byte[block_size];
        int bytes;
        // for verifying md5
        MessageDigest dig = MessageDigest.getInstance("MD5");
        while ((bytes = in.read(data, 0, block_size)) != -1) {
            out.write(data, 0, bytes);
            dig.update(data, 0, bytes);
        }
        in.close();
        in = null;
        out.close();
        out = null;

        java.math.BigInteger biggy = new java.math.BigInteger(1, dig.digest());
        String md5check = biggy.toString(16);
        if (!md5sum.equals(md5check)) {
            throw new SQLException("Jar could not be fetched due to data mismatch.\n" + "Expected md5sum: "
                    + md5sum + "; got " + md5check);
        }
    } catch (Throwable e) {
        throw new SQLException(e);
    } finally {
        try {
            if (in != null)
                in.close();
            if (out != null)
                out.close();
        } catch (IOException e) {
            //pass
        }
    }
}

From source file:com.sun.socialsite.util.Utilities.java

public static void copyInputToOutput(InputStream input, OutputStream output) throws IOException {
    BufferedInputStream in = new BufferedInputStream(input);
    BufferedOutputStream out = new BufferedOutputStream(output);
    byte buffer[] = new byte[8192];
    for (int count = 0; count != -1;) {
        count = in.read(buffer, 0, 8192);
        if (count != -1)
            out.write(buffer, 0, count);
    }/*ww  w . j  a va2 s  .  co  m*/

    try {
        in.close();
        out.close();
    } catch (IOException ex) {
        throw new IOException("Closing file streams, " + ex.getMessage());
    }
}

From source file:com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.java

/**
 * download file url and save it/* www .  j  av  a2 s . c om*/
 *
 * @param url
 */
public static String downloadFile(String url) {
    int BYTE_ARRAY_SIZE = 1024;
    int CONNECTION_TIMEOUT = 30000;
    int READ_TIMEOUT = 30000;

    // downloading cover image and saving it into file
    try {
        URL imageUrl = new URL(URLDecoder.decode(url));
        URLConnection conn = imageUrl.openConnection();
        conn.setConnectTimeout(CONNECTION_TIMEOUT);
        conn.setReadTimeout(READ_TIMEOUT);
        BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());

        File resFile = new File(
                Statics.moduleCachePath + File.separator + com.appbuilder.sdk.android.Utils.md5(url));
        if (!resFile.exists()) {
            resFile.createNewFile();
        }

        FileOutputStream fos = new FileOutputStream(resFile);
        int current = 0;
        byte[] buf = new byte[BYTE_ARRAY_SIZE];
        Arrays.fill(buf, (byte) 0);
        while ((current = bis.read(buf, 0, BYTE_ARRAY_SIZE)) != -1) {
            fos.write(buf, 0, current);
            Arrays.fill(buf, (byte) 0);
        }

        bis.close();
        fos.flush();
        fos.close();
        Log.d("", "");
        return resFile.getAbsolutePath();
    } catch (SocketTimeoutException e) {
        return null;
    } catch (IllegalArgumentException e) {
        return null;
    } catch (Exception e) {
        return null;
    }
}

From source file:com.alibaba.akita.io.HttpInvoker.java

private static byte[] retrieveImageData(InputStream inputStream, int fileSize, ProgressBar progressBar)
        throws IOException {

    // determine the remoteimageview size and allocate a buffer
    //Log.d(TAG, "fetching remoteimageview " + imgUrl + " (" +
    //        (fileSize <= 0 ? "size unknown" : Long.toString(fileSize)) + ")");
    BufferedInputStream istream = new BufferedInputStream(inputStream);

    try {//from  ww  w  .j a v a 2 s  .c om
        if (fileSize <= 0) {
            Log.w(TAG, "Server did not set a Content-Length header, will default to buffer size of "
                    + DEFAULT_BUFFER_SIZE + " bytes");
            ByteArrayOutputStream buf = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);
            byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
            int bytesRead = 0;
            while (bytesRead != -1) {
                bytesRead = istream.read(buffer, 0, DEFAULT_BUFFER_SIZE);
                if (bytesRead > 0)
                    buf.write(buffer, 0, bytesRead);
            }
            return buf.toByteArray();
        } else {
            byte[] imageData = new byte[fileSize];

            int bytesRead = 0;
            int offset = 0;
            while (bytesRead != -1 && offset < fileSize) {
                bytesRead = istream.read(imageData, offset, fileSize - offset);
                offset += bytesRead;
                // process reporting
                try {
                    if (progressBar != null) {
                        progressBar.setProgress(offset * 100 / fileSize);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return imageData;
        }
    } finally {
        // clean up
        try {
            istream.close();
            inputStream.close();
        } catch (Exception ignore) {
        }
    }
}