Example usage for java.io BufferedInputStream close

List of usage examples for java.io BufferedInputStream close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes this input stream and releases any system resources associated with the stream.

Usage

From source file:com.concursive.connect.web.modules.documents.beans.FileDownload.java

public static void send(OutputStream outputStream, InputStream is) throws Exception {
    BufferedInputStream inputStream = new BufferedInputStream(is);
    byte[] buf = new byte[4 * 1024];
    // 4K buffer/*from   ww  w. j  a v a 2 s.c  o  m*/
    int len;
    while ((len = inputStream.read(buf, 0, buf.length)) != -1) {
        outputStream.write(buf, 0, len);
    }
    outputStream.flush();
    outputStream.close();
    inputStream.close();
}

From source file:Main.java

/**
 * Copies file contents from source to destination. Makes up for the lack of
 * file copying utilities in Java/*  w w w  .  j  ava  2s.c  o m*/
 */
public static boolean copy(File source, File destination) {
    BufferedInputStream fin = null;
    BufferedOutputStream fout = null;
    try {
        int bufSize = 8 * 1024;
        fin = new BufferedInputStream(new FileInputStream(source), bufSize);
        fout = new BufferedOutputStream(new FileOutputStream(destination), bufSize);
        copyPipe(fin, fout, bufSize);
    } catch (IOException ioex) {
        return false;
    } catch (SecurityException sx) {
        return false;
    } finally {
        if (fin != null) {
            try {
                fin.close();
            } catch (IOException cioex) {
            }
        }
        if (fout != null) {
            try {
                fout.close();
            } catch (IOException cioex) {
            }
        }
    }
    return true;
}

From source file:org.dataone.proto.trove.mn.http.client.DataHttpClientHandler.java

public static synchronized String executePost(HttpClient httpclient, HttpPost httpPost)
        throws ServiceFailure, NotFound, InvalidToken, NotAuthorized, IdentifierNotUnique, UnsupportedType,
        InsufficientResources, InvalidSystemMetadata, NotImplemented, InvalidCredentials, InvalidRequest,
        AuthenticationTimeout, UnsupportedMetadataType, HttpException {
    String response = null;//from   w  ww .  j  a  va 2 s.  com

    try {
        HttpResponse httpResponse = httpclient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
            HttpEntity resEntity = httpResponse.getEntity();
            if (resEntity != null) {
                logger.debug("Response content length: " + resEntity.getContentLength());
                logger.debug("Chunked?: " + resEntity.isChunked());
                BufferedInputStream in = new BufferedInputStream(resEntity.getContent());
                ByteArrayOutputStream resOutputStream = new ByteArrayOutputStream();
                byte[] buff = new byte[32 * 1024];
                int len;
                while ((len = in.read(buff)) > 0) {
                    resOutputStream.write(buff, 0, len);
                }
                response = new String(resOutputStream.toByteArray());
                logger.debug(response);
                resOutputStream.close();
                in.close();
            }
        } else {
            HttpExceptionHandler.deserializeAndThrowException(httpResponse);
        }
    } catch (IOException ex) {
        throw new ServiceFailure("1002", ex.getMessage());
    }
    return response;
}

From source file:edu.du.penrose.systems.fedoraProxy.web.bus.ProxyController.java

/**
 * Call the HttpMethod and write all results and status to the HTTP response
 * object./*  ww w  .j a  v  a2s  . c o  m*/
 * 
 * THIS IS THE REQUEST WE NEED TO DUPLICATE GET
 * /fedora/get/codu:72/ECTD_test_1_access.pdf HTTP/1.1 Host: localhost:8080
 * Connection: keep-alive Accept:
 * application/xml,application/xhtml+xml,text/
 * html;q=0.9,text/plain;q=0.8,image/png,*;q=0.5 User-Agent: Mozilla/5.0
 * (X11; U; Linux x86_64; en-US) AppleWebKit/534.10 (KHTML, like Gecko)
 * Chrome/8.0.552.215 Safari/534.10 Accept-Encoding: gzip,deflate,sdch
 * Accept-Language: en-US,en;q=0.8 Accept-Charset:
 * ISO-8859-1,utf-8;q=0.7,*;q=0.3 Cookie: fez_list=YjowOw%3D%3D
 * 
 * ACTUAL SENT GET /fedora/get/codu:72/ECTD_test_1_access.pdf HTTP/1.1
 * Accept:
 * application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q
 * =0.8,image/png,*;q=0.5 Connection: keep-alive Accept-Encoding:
 * gzip,deflate,sdch Accept-Language: en-US,en;q=0.8 Accept-Charset:
 * ISO-8859-1,utf-8;q=0.7,*;q=0.3 : User-Agent: Jakarta
 * Commons-HttpClient/3.1 Host: localhost:8080
 * 
 * @param proxyCommand
 * @param response
 * @param authenicate true to set Preemptive authentication
 */
public static void executeMethod(String proxyCommand, HttpServletResponse response, boolean authenicate) {
    HttpClient theClient = new HttpClient();

    HttpMethod method = new GetMethod(proxyCommand);

    setDefaultHeaders(method);

    setAdrCredentials(theClient, authenicate);

    try {
        theClient.executeMethod(method);
        response.setStatus(method.getStatusCode());

        // Set the content type, as it comes from the server
        Header[] headers = method.getResponseHeaders();
        for (Header header : headers) {

            if ("Content-Type".equalsIgnoreCase(header.getName())) {
                response.setContentType(header.getValue());
            }

            /**
             * Copy all headers, except Transfer-Encoding which is getting set
             * set elsewhere. At this point response.containsHeader(
             * "Transfer-Encoding" ) is false, however it is getting set twice
             * according to wireshark, therefore we do not set it here.
             */
            if (!header.getName().equalsIgnoreCase("Transfer-Encoding")) {
                response.setHeader(header.getName(), header.getValue());
            }
        }

        // Write the body, flush and close

        InputStream is = method.getResponseBodyAsStream();

        BufferedInputStream bis = new BufferedInputStream(is);

        StringBuffer sb = new StringBuffer();
        byte[] bytes = new byte[8192]; // reading as chunk of 8192 bytes
        int count = bis.read(bytes);
        while (count != -1 && count <= 8192) {
            response.getOutputStream().write(bytes, 0, count);
            count = bis.read(bytes);
        }

        bis.close();
        response.getOutputStream().flush();
        response.getOutputStream().close();
    } catch (Exception e) {
        logger.error(e.getMessage());
    } finally {
        method.releaseConnection();
    }
}

From source file:Main.java

/**
 * Save URL contents to a file.//  w  ww  .ja  va  2s  . co m
 */
public static boolean copy(URL from, File to) {
    BufferedInputStream urlin = null;
    BufferedOutputStream fout = null;
    try {
        int bufSize = 8 * 1024;
        urlin = new BufferedInputStream(from.openConnection().getInputStream(), bufSize);
        fout = new BufferedOutputStream(new FileOutputStream(to), bufSize);
        copyPipe(urlin, fout, bufSize);
    } catch (IOException ioex) {
        return false;
    } catch (SecurityException sx) {
        return false;
    } finally {
        if (urlin != null) {
            try {
                urlin.close();
            } catch (IOException cioex) {
            }
        }
        if (fout != null) {
            try {
                fout.close();
            } catch (IOException cioex) {
            }
        }
    }
    return true;
}

From source file:com.runwaysdk.controller.ErrorUtility.java

private static String decompress(String message) {
    try {// w ww  . ja  v a 2 s .  c om
        byte[] bytes = Base64.decode(message);

        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        BufferedInputStream bufis = new BufferedInputStream(new GZIPInputStream(bis));
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buf = new byte[1024];
        int len;
        while ((len = bufis.read(buf)) > 0) {
            bos.write(buf, 0, len);
        }
        String retval = bos.toString();
        bis.close();
        bufis.close();
        bos.close();
        return retval;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.cloudera.recordbreaker.analyzer.UnknownTextDataDescriptor.java

public static boolean isTextData(FileSystem fs, Path p) {
    try {//w ww  .ja v  a 2 s  .  c  o  m
        BufferedInputStream in = new BufferedInputStream(fs.open(p));
        try {
            byte buf[] = new byte[1024];
            int numBytes = in.read(buf);
            if (numBytes < 0) {
                return false;
            }
            int numASCIIChars = 0;
            for (int i = 0; i < numBytes; i++) {
                if (buf[i] >= 32 && buf[i] < 128) {
                    numASCIIChars++;
                }
            }
            return ((numASCIIChars / (1.0 * numBytes)) > asciiThreshold);
        } finally {
            in.close();
        }
    } catch (IOException iex) {
        return false;
    }
}

From source file:Main.java

public static Object readBeanFromXml(String path) throws Exception {
    FileInputStream fis = null;/*  w w  w  .ja  va  2  s  .c o  m*/
    Object aplicacion = null;
    BufferedInputStream bis = null;
    try {
        fis = new FileInputStream(path);
        bis = new BufferedInputStream(fis);
        XMLDecoder xmlDecoder = new XMLDecoder(bis);
        aplicacion = (Object) xmlDecoder.readObject();

    } catch (FileNotFoundException ex) {
        throw new Exception("File to read not found.", ex);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException ex) {
                throw new Exception("File to close FileInputStream after read.", ex);
            }
        }

        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ex) {
                throw new Exception("File to close BufferedInputStream after read.", ex);
            }
        }
    }

    return aplicacion;

}

From source file:de.uzk.hki.da.pkg.MetsConsistencyChecker.java

/**
 * Calculate hash./*  w  w w. ja  va2s . c  o m*/
 *
 * @param algorithm the algorithm
 * @param file the file
 * @return the string
 * @throws Exception the exception
 */
private static String calculateHash(MessageDigest algorithm, File file) throws Exception {

    FileInputStream fis = new FileInputStream(file);
    BufferedInputStream bis = new BufferedInputStream(fis);
    DigestInputStream dis = new DigestInputStream(bis, algorithm);

    // read the file and update the hash calculation
    while (dis.read() != -1)
        ;

    // get the hash value as byte array
    byte[] hash = algorithm.digest();

    fis.close();
    bis.close();
    dis.close();

    return byteArray2Hex(hash);

}

From source file:fr.paris.lutece.plugins.updater.service.UpdateService.java

/**
 * Copies data from an input stream to an output stream.
 * @param inStream The input stream//from w  ww . j ava 2s  .  co  m
 * @param outStream The output stream
 * @throws IOException If an I/O error occurs
 */
private static void copyStream(InputStream inStream, OutputStream outStream) throws IOException {
    BufferedInputStream inBufferedStream = new BufferedInputStream(inStream);
    BufferedOutputStream outBufferedStream = new BufferedOutputStream(outStream);

    int nByte;

    while ((nByte = inBufferedStream.read()) > -1) {
        outBufferedStream.write(nByte);
    }

    outBufferedStream.close();
    inBufferedStream.close();
}