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:fr.gouv.finances.dgfip.xemelios.importers.DefaultImporter.java

protected static String getFileEncoding(File f) throws IOException {
    String ret = "UTF-8";
    try {//from   ww  w.  j a v a  2s. com
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
        byte[] bb = new byte[255];
        int read = bis.read(bb);
        if (read < 255) {
            logger.info("while reading " + f.getName() + " for getFileEncoding(), can only read " + read
                    + " bytes.");
        }
        String buff = new String(bb);
        buff = buff.substring(buff.indexOf("<?"));
        buff = buff.substring(0, buff.indexOf("?>") + 2);
        String header = buff;
        int encodingPos = header.indexOf("encoding=");
        if (encodingPos >= 0) {
            String s = header.substring(encodingPos + 9);
            if (s.startsWith("\"")) {
                ret = s.substring(1, s.indexOf('"', 1));
            } else if (s.startsWith("'")) {
                ret = s.substring(1, s.indexOf('\'', 1));
            } else {
                s = s.substring(0, s.length() - 2).trim();
                if (s.indexOf(' ') > 0) {
                    ret = s.substring(0, s.indexOf(' '));
                } else {
                    ret = s;
                }
            }
        } else {
            ret = "UTF-8";
        }
        bis.close();
    } catch (Exception ex) {
        logger.error("getFileEncoding(File)" + ex);
    }
    logger.debug("encoding=" + ret);
    return ret;
}

From source file:alpha.portal.webapp.controller.CardFormController.java

/**
 * Gets the payload./*from  w w  w  .ja v a2  s.  c o m*/
 * 
 * @param jspCard
 *            the jsp card
 * @param response
 *            the response
 * @return the payload
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
@RequestMapping(method = RequestMethod.POST, params = { "payloadGet" })
public String getPayload(final AlphaCard jspCard, final HttpServletResponse response) throws IOException {
    final AlphaCard alphaCard = this.alphaCardManager.get(jspCard.getAlphaCardIdentifier());
    final Payload payload = alphaCard.getPayload();

    if (payload != null) {

        final BufferedInputStream in = new BufferedInputStream(new ByteArrayInputStream(payload.getContent()));

        response.setBufferSize(payload.getContent().length);
        response.setContentType(payload.getMimeType());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + payload.getFilename() + "\"");
        response.setContentLength(payload.getContent().length);

        FileCopyUtils.copy(in, response.getOutputStream());
        in.close();
        response.getOutputStream().flush();
        response.getOutputStream().close();
    }

    final AlphaCardIdentifier identifier = alphaCard.getAlphaCardIdentifier();
    return "redirect:/caseform?caseId=" + identifier.getCaseId() + "&activeCardId=" + identifier.getCardId();
}

From source file:com.elevenpaths.googleindexretriever.GoogleSearch.java

public void getCaptcha(String image) {

    try {// w ww . j a  v a 2s .  co m
        URL obj = new URL(image);

        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        // add request header
        con.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0");
        con.addRequestProperty("Connection", "keep-alive");

        con.getResponseCode();
        tokenCookie = con.getHeaderField("Set-Cookie");

        // creating the input stream from google image
        BufferedInputStream in = new BufferedInputStream(con.getInputStream());
        // my local file writer, output stream
        BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("Captcha.png"));
        // until the end of data, keep saving into file.
        int i;
        while ((i = in.read()) != -1) {
            out.write(i);
        }
        out.flush();
        in.close();
        out.close();
        con.disconnect();
    } catch (MalformedURLException e) {

    } catch (IOException e) {
        // TODO: handle exception
    }

}

From source file:eu.eubrazilcc.lvl.core.io.FileCompressor.java

/**
 * Uncompress the content of a tarball file to the specified directory.
 * @param srcFile - the tarball to be uncompressed
 * @param outDir - directory where the files (and directories) extracted from the tarball will be written
 * @return the list of files (and directories) extracted from the tarball
 * @throws IOException when an exception occurs on uncompressing the tarball
 *//*from   ww  w .  j  a  va  2s.c  o  m*/
public static List<String> unGzipUnTar(final String srcFile, final String outDir) throws IOException {
    final List<String> uncompressedFiles = newArrayList();
    FileInputStream fileInputStream = null;
    BufferedInputStream bufferedInputStream = null;
    GzipCompressorInputStream gzipCompressorInputStream = null;
    TarArchiveInputStream tarArchiveInputStream = null;
    BufferedInputStream bufferedInputStream2 = null;

    try {
        forceMkdir(new File(outDir));
        fileInputStream = new FileInputStream(srcFile);
        bufferedInputStream = new BufferedInputStream(fileInputStream);
        gzipCompressorInputStream = new GzipCompressorInputStream(fileInputStream);
        tarArchiveInputStream = new TarArchiveInputStream(gzipCompressorInputStream);

        TarArchiveEntry entry = null;
        while ((entry = tarArchiveInputStream.getNextTarEntry()) != null) {
            final File outputFile = new File(outDir, entry.getName());
            if (entry.isDirectory()) {
                // attempting to write output directory
                if (!outputFile.exists()) {
                    // attempting to create output directory
                    if (!outputFile.mkdirs()) {
                        throw new IOException("Cannot create directory: " + outputFile.getCanonicalPath());
                    }
                }
            } else {
                // attempting to create output file
                final byte[] content = new byte[(int) entry.getSize()];
                tarArchiveInputStream.read(content, 0, content.length);
                final FileOutputStream outputFileStream = new FileOutputStream(outputFile);
                write(content, outputFileStream);
                outputFileStream.close();
                uncompressedFiles.add(outputFile.getCanonicalPath());
            }
        }
    } finally {
        if (bufferedInputStream2 != null) {
            bufferedInputStream2.close();
        }
        if (tarArchiveInputStream != null) {
            tarArchiveInputStream.close();
        }
        if (gzipCompressorInputStream != null) {
            gzipCompressorInputStream.close();
        }
        if (bufferedInputStream != null) {
            bufferedInputStream.close();
        }
        if (fileInputStream != null) {
            fileInputStream.close();
        }
    }
    return uncompressedFiles;
}

From source file:cn.edu.sdust.silence.itransfer.filemanage.FileManager.java

private void zip_folder(File file, ZipOutputStream zout) throws IOException {
    byte[] data = new byte[BUFFER];
    int read;// w  ww. jav a  2s.  co  m

    if (file.isFile()) {
        ZipEntry entry = new ZipEntry(file.getName());
        zout.putNextEntry(entry);
        BufferedInputStream instream = new BufferedInputStream(new FileInputStream(file));

        while ((read = instream.read(data, 0, BUFFER)) != -1)
            zout.write(data, 0, read);

        zout.closeEntry();
        instream.close();

    } else if (file.isDirectory()) {
        String[] list = file.list();
        int len = list.length;

        for (int i = 0; i < len; i++)
            zip_folder(new File(file.getPath() + "/" + list[i]), zout);
    }
}

From source file:com.servoy.extensions.plugins.http.HttpProvider.java

/**
 * Get media (binary data) such as images in a variable. It also supports gzip-ed content.
 * If this url is an https url that uses certificates unknown to Java
 * then you have to use the HttpClient so that smart client users will get the unknown certificate dialog that they then can accept
 * or you must make sure that those server certificates are stored in the cacerts of the java vm that is used (this is required for a web or headless client)
 *
 * @sample/*from  ww  w . j av a  2s . co m*/
 * var image_byte_array = plugins.http.getMediaData('http://www.cnn.com/cnn.gif');
 *
 * @param url 
 */
public byte[] js_getMediaData(String url) {
    if (url == null)
        return null;
    ByteArrayOutputStream sb = new ByteArrayOutputStream();
    try {
        URLConnection connection = createURLFromString(url).openConnection();

        if (timeout >= 0)
            connection.setConnectTimeout(timeout);
        InputStream is = connection.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        Utils.streamCopy(bis, sb);
        bis.close();
        is.close();
    } catch (Exception e) {
        Debug.error(e);
    }
    return sb.toByteArray();
}

From source file:iqq.app.core.service.impl.SkinServiceImpl.java

private Font loadFontFromFile(File file) {
    BufferedInputStream in = null;
    try {//from www  .  ja  v a 2 s. com
        in = new BufferedInputStream(new FileInputStream(file));
        Font font = Font.createFont(Font.TRUETYPE_FONT, in);
        return font;
    } catch (FileNotFoundException e) {
        LOG.warn("font " + file + "not found!", e);
    } catch (FontFormatException e) {
        LOG.warn("invalid font file!", e);
    } catch (IOException e) {
        LOG.warn("read font error!", e);
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                LOG.warn("close font file error!", e);
            }
        }
    }
    return null;
}

From source file:ResourceServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //get web.xml for display by a servlet
    String file = "/WEB-INF/web.xml";

    URL url = null;/* w w  w  .ja  v  a  2s. c  o m*/
    URLConnection urlConn = null;
    PrintWriter out = null;
    BufferedInputStream buf = null;
    try {
        out = response.getWriter();
        url = getServletContext().getResource(file);
        //set response header
        response.setContentType("text/xml");

        urlConn = url.openConnection();
        //establish connection with URL presenting web.xml
        urlConn.connect();
        buf = new BufferedInputStream(urlConn.getInputStream());
        int readBytes = 0;
        while ((readBytes = buf.read()) != -1)
            out.write(readBytes);
    } catch (MalformedURLException mue) {
        throw new ServletException(mue.getMessage());
    } catch (IOException ioe) {
        throw new ServletException(ioe.getMessage());
    } finally {
        if (out != null)
            out.close();
        if (buf != null)
            buf.close();
    }
}

From source file:com.surevine.alfresco.webscript.gsa.getallitems.GSANodePropertyServiceImpl.java

/**
 * This method isn't optimised for very large content items, and will break entirely with anything > 4Gb, but that's
 * more than fine given our use case//from  w  w  w. j a  va 2 s . c  o  m
 */
@Override
public String getContent(NodeRef nodeRef) {

    //People
    if (isNodeRefProfile(nodeRef)) {
        return escapeContentString(getUnescapedProfileContent(nodeRef));
    }

    //Things
    ContentReader reader = _contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);

    int dataSize = (int) getContentSize(nodeRef);
    if (dataSize > _maxItemSizeInBytes) {
        _logger.info("Truncating " + nodeRef + " from " + reader.getSize() + " to " + _maxItemSizeInBytes
                + " bytes");
        dataSize = _maxItemSizeInBytes;
    }

    byte[] data = new byte[dataSize]; //Seriously, you shouldn't be trying to get 4Gb of data using this method anyway
    BufferedInputStream bis = null;
    try {
        bis = new BufferedInputStream(reader.getContentInputStream());
        bis.read(data, 0, dataSize);
    } catch (Exception e) {
        throw new GSAProcessingException("Error reading content data for " + nodeRef, e, 100000);
    } finally {
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException e) {
                _logger.warn("Could not close byte array input stream - ignoring");
            }
        }
    }
    _logger.debug(data.length + " bytes of content data returned for " + nodeRef);
    return escapeContentString(data);
}

From source file:edu.stanford.epadd.launcher.Splash.java

/** not used any more
static class ShutdownTimerTask extends TimerTask {
// possibly could tie this timer with user activity
public void run() {//  w  w  w. j a va 2 s  .  c  o m
out.println ("Shutting down ePADD completely at time " +  formatDateLong(new GregorianCalendar()));
savedSystemOut.println ("Shutting down ePADD completely at time " +  formatDateLong(new GregorianCalendar()));
        
// maybe throw open a browser window to let user know muse is shutting down ??
System.exit(0); // kill the program
}
}
*/

// util methods
public static void copy_stream_to_file(InputStream is, String filename) throws IOException {
    int bufsize = 64 * 1024;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        File f = new File(filename);
        if (f.exists()) {
            // out.println ("File " + filename + " exists");
            boolean b = f.delete(); // best effort to delete file if it exists. this is because windows often complains about perms 
            if (!b)
                out.println("Warning: failed to delete " + filename);
        }
        bis = new BufferedInputStream(is, bufsize);
        bos = new BufferedOutputStream(new FileOutputStream(filename), bufsize);
        byte buf[] = new byte[bufsize];
        while (true) {
            int n = bis.read(buf);
            if (n <= 0)
                break;
            bos.write(buf, 0, n);
        }
    } catch (IOException ioe) {
        out.println("ERROR trying to copy data to file: " + filename + ", forging ahead nevertheless");
    } finally {
        if (bis != null)
            bis.close();
        if (bos != null)
            bos.close();
    }
}