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() throws IOException 

Source Link

Document

See the general contract of the read method of InputStream.

Usage

From source file:com.cloudhopper.commons.io.demo.FileServerMain.java

private static void saveFileFromUrl(URL url, String path) throws Exception {
    URLConnection urlc = url.openConnection();
    BufferedInputStream bis = new BufferedInputStream(urlc.getInputStream());
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(path)));
    int i;/* w  ww . j  av a  2s  . c  o  m*/
    while ((i = bis.read()) != -1) {
        bos.write(i);
    }
    bis.close();
    bos.close();
}

From source file:fr.asso.vieillescharrues.parseurs.TelechargeFichier.java

/**
 * Mthode statique grant le tlechargement de fichiers
 * @param url Adresse du fichier//from  ww  w.j ava  2 s .co  m
 * @param fichierDest Nom du ficher en local
 */
public static void DownloadFromUrl(URL url, String fichierDest) throws IOException {
    File file;
    if (fichierDest.endsWith(".jpg"))
        file = new File(PATH + "images/", fichierDest);
    else
        file = new File(PATH, fichierDest);
    file.getParentFile().mkdirs();
    URLConnection ucon = url.openConnection();

    try {
        tailleDistant = ucon.getHeaderFieldInt("Content-Length", 0); //Rcupre le header HTTP Content-Length
        tailleLocal = (int) file.length();
    } catch (Exception e) {
        e.printStackTrace();
    }
    // Compare les tailles des fichiers
    if ((tailleDistant == tailleLocal) && (tailleLocal != 0))
        return;

    InputStream is = ucon.getInputStream();
    BufferedInputStream bis = new BufferedInputStream(is);
    ByteArrayBuffer baf = new ByteArrayBuffer(50);
    int current = 0;
    while ((current = bis.read()) != -1) {
        baf.append((byte) current);
    }
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(baf.toByteArray());
    fos.close();
}

From source file:com.fastbootmobile.encore.api.common.HttpGet.java

/**
 * Downloads the data from the provided URL.
 * @param inUrl The URL to get from//w w  w  .  ja va2  s  .co m
 * @param query The query field. '?' + query will be appended automatically, and the query data
 *              MUST be encoded properly.
 * @return A byte array of the data
 */
public static byte[] getBytes(String inUrl, String query, boolean cached)
        throws IOException, RateLimitException {
    final String formattedUrl = inUrl + (query.isEmpty() ? "" : ("?" + query));

    Log.d(TAG, "Formatted URL: " + formattedUrl);

    URL url = new URL(formattedUrl);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestProperty("User-Agent", "OmniMusic/1.0-dev (http://www.omnirom.org)");
    urlConnection.setUseCaches(cached);
    urlConnection.setInstanceFollowRedirects(true);
    int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
    urlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
    try {
        final int status = urlConnection.getResponseCode();
        // MusicBrainz returns 503 Unavailable on rate limit errors. Parse the JSON anyway.
        if (status == HttpURLConnection.HTTP_OK) {
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            int contentLength = urlConnection.getContentLength();
            if (contentLength <= 0) {
                // No length? Let's allocate 100KB.
                contentLength = 100 * 1024;
            }
            ByteArrayBuffer bab = new ByteArrayBuffer(contentLength);
            BufferedInputStream bis = new BufferedInputStream(in);
            int character;

            while ((character = bis.read()) != -1) {
                bab.append(character);
            }
            return bab.toByteArray();
        } else if (status == HttpURLConnection.HTTP_NOT_FOUND) {
            // 404
            return new byte[] {};
        } else if (status == HttpURLConnection.HTTP_FORBIDDEN) {
            return new byte[] {};
        } else if (status == HttpURLConnection.HTTP_UNAVAILABLE) {
            throw new RateLimitException();
        } else if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == 307 /* HTTP/1.1 TEMPORARY REDIRECT */
                || status == HttpURLConnection.HTTP_SEE_OTHER) {
            // We've been redirected, follow the new URL
            final String followUrl = urlConnection.getHeaderField("Location");
            Log.e(TAG, "Redirected to: " + followUrl);
            return getBytes(followUrl, "", cached);
        } else {
            Log.e(TAG, "Error when fetching: " + formattedUrl + " (" + urlConnection.getResponseCode() + ")");
            return new byte[] {};
        }
    } finally {
        urlConnection.disconnect();
    }
}

From source file:MainServer.UploadServlet.java

public static void inputStream2File(InputStream is, String savePath) throws Exception {
    System.out.println("Save path:" + savePath);
    File file = new File(savePath);
    InputStream inputStream = is;
    BufferedInputStream fis = new BufferedInputStream(inputStream);
    FileOutputStream fos = new FileOutputStream(file);
    int f;//from w  w w .j a v  a  2  s  .c o m
    while ((f = fis.read()) != -1) {
        fos.write(f);
    }
    fos.flush();
    fos.close();
    fis.close();
    inputStream.close();
}

From source file:Main.java

public static String getResourceText(Context context, int resId) {
    InputStream is = null;//  www.  j a  v  a2s. com
    BufferedInputStream bis;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        is = context.getResources().openRawResource(resId);
        bis = new BufferedInputStream(is);
        int result = bis.read();
        while (result != -1) {
            byte b = (byte) result;
            baos.write(b);
            result = bis.read();
        }
    } catch (IOException e) {
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
        }
    }
    return baos.toString();
}

From source file:com.pwned.utils.VersionCheck.java

private static void _versionCheck() throws IOException {
    URL myURL = new URL(Constants.VERSIONCHECK_URL);
    URLConnection ucon = myURL.openConnection();
    InputStream is = ucon.getInputStream();
    BufferedInputStream bis = new BufferedInputStream(is);
    ByteArrayBuffer baf = new ByteArrayBuffer(50);
    int current = 0;
    while ((current = bis.read()) != -1) {
        baf.append((byte) current);
    }/*from  ww w  . j a  va 2s .co  m*/
    Logger.log("start version check", new String(baf.toByteArray()));
    try {
        currentVersionName = Integer.parseInt(new String(baf.toByteArray()));
    } catch (Exception e) {
        currentVersionName = 1;
    }
    ((Activity) context).runOnUiThread(returnRes);
}

From source file:Main.java

public static long downloadFileFromUrl(String urlPath, File file) {
    long size = 0;
    try {/*from w w  w.  j a  va 2s .c o m*/
        URL url = new URL(urlPath);
        HttpURLConnection httpurlconnection = (HttpURLConnection) url.openConnection();
        BufferedInputStream bufferedinputstream = new BufferedInputStream(httpurlconnection.getInputStream());
        BufferedOutputStream bufferedoutputstream = new BufferedOutputStream(new FileOutputStream(file));
        int i;
        while ((i = bufferedinputstream.read()) != -1) {
            bufferedoutputstream.write(i);
        }
        bufferedinputstream.close();
        bufferedoutputstream.close();
        httpurlconnection.disconnect();
        size = file.length();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return size;
}

From source file:com.mpower.mintel.android.application.MIntel.java

private static void copyAudioFiles(String[] assetName) {
    for (int i = 0; i < assetName.length; i++) {
        File file = new File(METADATA_PATH, assetName[i]);
        if (!file.exists()) {
            AssetManager mngr = getAppContext().getAssets();
            ByteArrayBuffer baf = new ByteArrayBuffer(2048);
            try {
                InputStream path = mngr.open(assetName[i]);
                BufferedInputStream bis = new BufferedInputStream(path, 1024);
                int current = 0;
                while ((current = bis.read()) != -1) {
                    baf.append((byte) current);
                }/*w  w w  .  j  a  v  a 2  s .  c  om*/
                byte[] bitmapdata = baf.toByteArray();

                FileOutputStream fos;
                fos = new FileOutputStream(file);
                fos.write(bitmapdata);
                fos.flush();
                fos.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

From source file:com.android.bandwidthtest.util.BandwidthTestUtil.java

/**
 * Download a given file from a target url to a given destination file.
 * @param targetUrl the url to download/*ww w  .  j av a2  s.co  m*/
 * @param file the {@link File} location where to save to
 * @return true if it succeeded
 */
public static boolean DownloadFromUrl(String targetUrl, File file) {
    try {
        URL url = new URL(targetUrl);
        Log.d(LOG_TAG, "Download begining");
        Log.d(LOG_TAG, "Download url:" + url);
        Log.d(LOG_TAG, "Downloaded file name:" + file.getAbsolutePath());
        URLConnection ucon = url.openConnection();
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();
    } catch (IOException e) {
        Log.d(LOG_TAG, "Failed to download file with error: " + e);
        return false;
    }
    return true;
}

From source file:subhan.portal.config.Util.java

public static void downloadFromUrl(String downloadUrl, String fileName) throws IOException {
    File root = android.os.Environment.getExternalStorageDirectory(); // path ke sdcard

    File dir = new File(root.getAbsolutePath() + "/youread"); // path ke folder

    if (dir.exists() == false) { // cek folder eksistensi
        dir.mkdirs(); // kalau belum ada, dibuat
    }/*  w  w w  .jav  a  2  s . c  o m*/

    URL url = new URL(downloadUrl); // you can write here any link
    File file = new File(dir, fileName);

    // Open a connection to that URL. 
    URLConnection ucon = url.openConnection();

    // Define InputStreams to read from the URLConnection. 
    InputStream is = ucon.getInputStream();
    BufferedInputStream bis = new BufferedInputStream(is);

    // Read bytes to the Buffer until there is nothing more to read(-1).
    ByteArrayBuffer baf = new ByteArrayBuffer(5000);
    int current = 0;
    while ((current = bis.read()) != -1) {
        baf.append((byte) current);
    }

    // Convert the Bytes read to a String. 
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(baf.toByteArray());
    fos.flush();
    fos.close();
}