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 int read(byte b[]) throws IOException 

Source Link

Document

Reads up to b.length bytes of data from this input stream into an array of bytes.

Usage

From source file:eu.liveandgov.ar.utilities.Download_Data.java

/**                      DownAndCopy
 * //from ww  w.j av  a 2  s  .  c  om
 * Download file from URL and Copy to Android file system folder
 * 
 * @param fileUrl
 * @param StringAndroidPath
 */
public static boolean DownAndCopy(String fileUrlSTR, String StringAndroidPath, boolean preservefilename,
        String Caller) {

    if (compareRemoteWithLocal(fileUrlSTR, StringAndroidPath)) {
        //Log.e("fileUrlSTR", "SKIP WITH HASH");
        return true;
    } else {
        Log.e("TRY TO DOWNLOAD BY " + Caller, fileUrlSTR);
    }

    SimpleDateFormat sdf = new SimpleDateFormat("mm");

    // Check if downloaded at least just 2 minutes ago
    for (String[] mem : MemDown)
        if (fileUrlSTR.equals(mem[0])) {
            int diff = Integer.parseInt(sdf.format(new Date())) - Integer.parseInt(mem[1]);
            Log.e("diff", " " + diff);
            if (diff < 2) {
                Log.d("Download_Data", "I am not downloading " + fileUrlSTR + " because it was downloaded "
                        + diff + " minutes ago");
                return true;
            }
        }

    if (!OS_Utils.exists(fileUrlSTR)) {
        Log.e("Download_Data", "URL: " + fileUrlSTR + " called from " + Caller + " not exists to copy it to "
                + StringAndroidPath);
        return false;
    }

    int DEBUG_FLAG = 0;

    HttpURLConnection conn;
    URL fileUrl = null;
    try {
        fileUrl = new URL(fileUrlSTR);
    } catch (MalformedURLException e1) {
        return false;
    }

    try {
        conn = (HttpURLConnection) fileUrl.openConnection();

        DEBUG_FLAG = 1;

        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(100);

        DEBUG_FLAG = 2;

        int current = 0;
        byte[] buffer = new byte[10];
        while ((current = bis.read(buffer)) != -1)
            baf.append(buffer, 0, current);

        DEBUG_FLAG = 3;

        /* Convert the Bytes read to a String. */
        File fileAndroid;

        try {

            if (preservefilename) {
                int iSlash = fileUrlSTR.lastIndexOf("/");
                fileAndroid = new File(StringAndroidPath + "/" + fileUrlSTR.substring(iSlash + 1));
            } else
                fileAndroid = new File(StringAndroidPath);

        } catch (Exception e) {
            Log.e("Download_Data.DownAndCopy", "I can not create " + StringAndroidPath);
            bis.close();
            conn.disconnect();
            return false;
        }

        DEBUG_FLAG = 4;

        FileOutputStream fos = new FileOutputStream(fileAndroid);
        fos.write(baf.toByteArray());

        DEBUG_FLAG = 5;

        bis.close();
        fos.close();
        conn.disconnect();

        MemDown.add(new String[] { fileUrlSTR, sdf.format(new Date()) });

        return true; //returns including the filename
    } catch (IOException e) {
        Log.e("Download_Data", "Download_Data: Error when trying to download:  " + fileUrl.toString() + " to "
                + StringAndroidPath + " DEBUG_FLAG=" + DEBUG_FLAG);
        return false;
    }

}

From source file:modnlp.capte.AlignerUtils.java

@SuppressWarnings("deprecation")
/* This method creates the HTTP connection to the server 
 * and sends the POST request with the two files for alignment,
 * /*from w  w  w .  j ava 2 s . com*/
 * The server returns the aligned file as the response to the post request, 
 * which is delimited by the tag <beginalignment> which separates the file
 * from the rest of the POST request
 * 
 * 
 * 
 */
public static String MultiPartFileUpload(String source, String target) throws IOException {
    String response = "";
    String serverline = System.getProperty("capte.align.server"); //"http://ronaldo.cs.tcd.ie:80/~gplynch/aling.cgi";   
    PostMethod filePost = new PostMethod(serverline);
    // Send any XML file as the body of the POST request
    File f1 = new File(source);
    File f2 = new File(target);
    System.out.println(f1.getName());
    System.out.println(f2.getName());
    System.out.println("File1 Length = " + f1.length());
    System.out.println("File2 Length = " + f2.length());
    Part[] parts = {

            new StringPart("param_name", "value"), new FilePart(f2.getName(), f2),
            new FilePart(f1.getName(), f1) };
    filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
    HttpClient client = new HttpClient();
    int status = client.executeMethod(filePost);
    String res = "";
    InputStream is = filePost.getResponseBodyAsStream();
    Header[] heads = filePost.getResponseHeaders();
    Header[] feet = filePost.getResponseFooters();
    BufferedInputStream bis = new BufferedInputStream(is);

    String datastr = null;
    StringBuffer sb = new StringBuffer();
    byte[] bytes = new byte[8192]; // reading as chunk of 8192
    int count = bis.read(bytes);
    while (count != -1 && count <= 8192) {
        datastr = new String(bytes, "UTF8");

        sb.append(datastr);
        count = bis.read(bytes);
    }

    bis.close();
    res = sb.toString();

    System.out.println("----------------------------------------");
    System.out.println("Status is:" + status);
    //System.out.println(res);
    /* for debugging
    for(int i = 0 ;i < heads.length ;i++){
      System.out.println(heads[i].toString());
                   
    }
    for(int j = 0 ;j < feet.length ;j++){
      System.out.println(feet[j].toString());
                   
    }
    */
    filePost.releaseConnection();
    String[] handle = res.split("<beginalignment>");
    //Check for errors in the header
    // System.out.println(handle[0]);
    //Return the required text
    String ho = "";
    if (handle.length < 2) {
        System.out.println("Server error during alignment, check file encodings");
        ho = "error";
    } else {
        ho = handle[1];
    }
    return ho;

}

From source file:Main.java

public static void fastBufferFileCopy(File source, File target) {
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    long start = System.currentTimeMillis();
    FileInputStream fis = null;/*www.jav a2  s. c om*/
    FileOutputStream fos = null;
    long size = source.length();
    try {
        fis = new FileInputStream(source);
        bis = new BufferedInputStream(fis);
        fos = new FileOutputStream(target);
        bos = new BufferedOutputStream(fos);

        byte[] barr = new byte[Math.min((int) size, 1 << 20)];
        int read = 0;
        while ((read = bis.read(barr)) != -1) {
            bos.write(barr, 0, read);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        close(fis);
        close(fos);
        close(bis);
        close(bos);
    }
    long end = System.currentTimeMillis();

    String srcPath = source.getAbsolutePath();
    Log.d("Copied " + srcPath + " to " + target,
            ", took " + (end - start) / 1000 + " ms, total size " + nf.format(size) + " Bytes, speed "
                    + ((end - start > 0) ? nf.format(size / (end - start)) : 0) + "KB/s");
}

From source file:Main.java

private static void downloadResource(String from, String to) {
    OutputStream outputStream = null;
    BufferedInputStream inputStream = null;
    HttpURLConnection connection = null;
    URL url;/*  w  w w .  ja v a  2s  .  c  o m*/
    byte[] buffer = new byte[1024];

    try {
        url = new URL(from);

        connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.connect();
        outputStream = new FileOutputStream(to);

        inputStream = new BufferedInputStream(url.openStream());
        int read;

        while ((read = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, read);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (outputStream != null)
            try {
                outputStream.close();
            } catch (IOException e) {
            }
        if (inputStream != null)
            try {
                inputStream.close();
            } catch (IOException e) {
            }
        if (connection != null)
            connection.disconnect();
    }
}

From source file:org.ametro.util.WebUtil.java

public static void downloadFileUnchecked(Object context, URI uri, File file, IDownloadListener listener)
        throws Exception {
    BufferedInputStream strm = null;
    if (listener != null) {
        listener.onBegin(context, file);
    }/*from w w w .j  a  va2 s  .  c o  m*/
    try {
        HttpClient client = ApplicationEx.getInstance().getHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(uri);
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            long total = (int) entity.getContentLength();
            long position = 0;

            if (file.exists()) {
                file.delete();
            }

            BufferedInputStream in = null;
            BufferedOutputStream out = null;
            try {
                in = new BufferedInputStream(entity.getContent());
                out = new BufferedOutputStream(new FileOutputStream(file));
                byte[] bytes = new byte[2048];
                for (int c = in.read(bytes); c != -1; c = in.read(bytes)) {
                    out.write(bytes, 0, c);
                    position += c;
                    if (listener != null) {
                        if (!listener.onUpdate(context, position, total)) {
                            throw new DownloadCanceledException();
                        }
                    }
                }

            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (Exception e) {
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (Exception e) {
                    }
                }
            }
            if (listener != null) {
                listener.onDone(context, file);
            }
        } else {
            String message = "Failed to download URL " + uri.toString() + " due error " + status.getStatusCode()
                    + " " + status.getReasonPhrase();
            throw new Exception(message);
        }
    } finally {
        if (strm != null) {
            try {
                strm.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:org.ametro.util.WebUtil.java

public static void downloadFile(Object context, URI uri, File file, boolean reuse, IDownloadListener listener) {
    BufferedInputStream strm = null;
    if (listener != null) {
        listener.onBegin(context, file);
    }/*from  w ww . j  a  v a 2  s.c  o  m*/
    try {
        HttpClient client = ApplicationEx.getInstance().getHttpClient();
        HttpGet request = new HttpGet();
        request.setURI(uri);
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();
        if (status.getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            long total = (int) entity.getContentLength();
            long position = 0;
            if (!(file.exists() && reuse && file.length() == total)) {
                if (file.exists()) {
                    file.delete();
                }
                BufferedInputStream in = null;
                BufferedOutputStream out = null;
                try {
                    in = new BufferedInputStream(entity.getContent());
                    out = new BufferedOutputStream(new FileOutputStream(file));
                    byte[] bytes = new byte[2048];
                    for (int c = in.read(bytes); c != -1; c = in.read(bytes)) {
                        out.write(bytes, 0, c);
                        position += c;
                        if (listener != null) {
                            if (!listener.onUpdate(context, position, total)) {
                                throw new DownloadCanceledException();
                            }
                        }
                    }

                } finally {
                    if (in != null) {
                        try {
                            in.close();
                        } catch (Exception e) {
                        }
                    }
                    if (out != null) {
                        try {
                            out.close();
                        } catch (Exception e) {
                        }
                    }
                }
            }
            if (listener != null) {
                listener.onDone(context, file);
            }
        } else {
            String message = "Failed to download URL " + uri.toString() + " due error " + status.getStatusCode()
                    + " " + status.getReasonPhrase();
            throw new Exception(message);
        }
    } catch (DownloadCanceledException ex) {
        if (listener != null) {
            listener.onCanceled(context, file);
        }
    } catch (Exception ex) {
        if (listener != null) {
            listener.onFailed(context, file, ex);
        }
    } finally {
        if (strm != null) {
            try {
                strm.close();
            } catch (IOException ex) {
            }
        }
    }
}

From source file:org.openo.nfvo.vnfmadapter.service.csm.connect.AbstractSslContext.java

/**readSSLConfToJson
 * @return/*from  w  w w  .  j  a va2  s  .c  om*/
 * @throws IOException
 * @since NFVO 0.5
 */
public static JSONObject readSSLConfToJson() throws IOException {
    JSONObject sslJson = null;
    InputStream ins = null;
    BufferedInputStream bins = null;
    String fileContent = "";

    String fileName = SystemEnvVariablesFactory.getInstance().getAppRoot()
            + System.getProperty("file.separator") + "etc" + System.getProperty("file.separator") + "conf"
            + System.getProperty("file.separator") + "sslconf.json";

    try {
        ins = new FileInputStream(fileName);
        bins = new BufferedInputStream(ins);

        byte[] contentByte = new byte[ins.available()];
        int num = bins.read(contentByte);

        if (num > 0) {
            fileContent = new String(contentByte);
        }
        sslJson = JSONObject.fromObject(fileContent);
    } catch (FileNotFoundException e) {
        LOG.error(fileName + "is not found!", e);
    } catch (Exception e) {
        LOG.error("read sslconf file fail.please check if the 'sslconf.json' is exist.");
    } finally {
        if (ins != null) {
            ins.close();
        }
        if (bins != null) {
            bins.close();
        }
    }

    return sslJson;
}

From source file:com.android.volley.toolbox.http.HurlStack.java

/**
 * Perform a multipart request on a connection
 *
 * @param connection The Connection to perform the multi part request
 * @param request    param additionalHeaders
 *                   param multipartParams
 *                   The params to add to the Multi Part request
 *                   param filesToUpload
 *                   The files to upload
 * @throws ProtocolException/*from ww  w . j ava2 s.c o m*/
 */
private static void setConnectionParametersForMultipartRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, ProtocolException {

    Map<String, File> filesToUpload = request.getFilesToUpload();
    if (filesToUpload != null) {
        for (String key : filesToUpload.keySet()) {
            File file = filesToUpload.get(key);

            if (file == null || !file.exists()) {
                throw new IOException(String.format("File not found: %s", file.getAbsolutePath()));
            }
            if (file.isDirectory()) {
                throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath()));
            }
        }
    }

    final int curTime = (int) (System.currentTimeMillis() / 1000);
    final String boundary = BOUNDARY_PREFIX + curTime;
    StringBuilder sb = new StringBuilder();
    Map<String, MultiPartParam> multipartParams = request.getMultiPartParams();
    for (String key : multipartParams.keySet()) {
        MultiPartParam param = multipartParams.get(key);

        sb.append(boundary).append(CRLF)
                .append(String.format(HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA, key)).append(CRLF)
                .append(HEADER_CONTENT_TYPE + COLON_SPACE).append(param.contentType).append(CRLF).append(CRLF)
                .append(param.value).append(CRLF);
    }
    final String charset = request.getParamsEncoding();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setRequestProperty(HEADER_CONTENT_TYPE, String.format(CONTENT_TYPE_MULTIPART, charset, curTime));
    //        connection.setChunkedStreamingMode(0);

    PrintWriter writer = null;
    try {
        OutputStream out = connection.getOutputStream();
        writer = new PrintWriter(new OutputStreamWriter(out, charset), true);

        writer.append(sb).flush();

        for (String key : filesToUpload.keySet()) {

            File file = filesToUpload.get(key);

            writer.append(boundary).append(CRLF)
                    .append(String.format(
                            HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA + SEMICOLON_SPACE + FILENAME,
                            key, file.getName()))
                    .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + CONTENT_TYPE_OCTET_STREAM)
                    .append(CRLF).append(HEADER_CONTENT_TRANSFER_ENCODING + COLON_SPACE + BINARY).append(CRLF)
                    .append(CRLF).flush();

            BufferedInputStream input = null;
            try {
                input = new BufferedInputStream(new FileInputStream(file));
                int bufferLength = 0;

                byte[] buffer = new byte[1024];
                while ((bufferLength = input.read(buffer)) > 0) {
                    out.write(buffer, 0, bufferLength);
                }
                out.flush(); // Important! Output cannot be closed. Close of
                // writer will close
                // output as well.
            } finally {
                if (input != null)
                    try {
                        input.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
            }
            writer.append(CRLF).flush(); // CRLF is important! It indicates
            // end of binary
            // boundary.
        }

        // End of multipart/form-data.
        writer.append(boundary).append(BOUNDARY_PREFIX).append(CRLF).flush();

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        if (writer != null) {
            writer.close();
        }
    }
}

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

private static void recurseFiles(JarOutputStream jos, File file, String s)
        throws IOException, FileNotFoundException {

    if (file.isDirectory()) {
        s = s + file.getName() + "/";
        jos.putNextEntry(new JarEntry(s));
        String as[] = file.list();
        if (as != null) {
            for (int i = 0; i < as.length; i++)
                recurseFiles(jos, new File(file, as[i]), s);
        }/*from   w  w  w.j  a va2s.c om*/
    } else {
        if (file.getName().endsWith("MANIFEST.MF") || file.getName().endsWith("META-INF/MANIFEST.MF")) {
            return;
        }
        JarEntry jarentry = new JarEntry(s + file.getName());
        FileInputStream fileinputstream = new FileInputStream(file);
        BufferedInputStream bufferedinputstream = new BufferedInputStream(fileinputstream);
        jos.putNextEntry(jarentry);
        while ((len = bufferedinputstream.read(buf)) >= 0) {
            jos.write(buf, 0, len);
        }
        bufferedinputstream.close();
        jos.closeEntry();
    }
}

From source file:Main.java

public static void downloadImage(String imageUrl) {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        Log.d("TAG", "monted sdcard");
    } else {/*w  w w.j a  v a  2s.  com*/
        Log.d("TAG", "has no sdcard");
    }
    HttpURLConnection con = null;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    BufferedInputStream bis = null;
    File imageFile = null;
    try {
        URL url = new URL(imageUrl);
        con = (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(5 * 1000);
        con.setReadTimeout(15 * 1000);
        con.setDoInput(true);
        con.setDoOutput(true);
        bis = new BufferedInputStream(con.getInputStream());
        imageFile = new File(getImagePath(imageUrl));
        fos = new FileOutputStream(imageFile);
        bos = new BufferedOutputStream(fos);
        byte[] b = new byte[1024];
        int length;
        while ((length = bis.read(b)) != -1) {
            bos.write(b, 0, length);
            bos.flush();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
            if (con != null) {
                con.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (imageFile != null) {
    }
}