Example usage for java.io BufferedInputStream BufferedInputStream

List of usage examples for java.io BufferedInputStream BufferedInputStream

Introduction

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

Prototype

public BufferedInputStream(InputStream in) 

Source Link

Document

Creates a BufferedInputStream and saves its argument, the input stream in, for later use.

Usage

From source file:com.smash.revolance.ui.model.helper.ArchiveHelper.java

public static File buildArchive(File archive, File... files) throws FileNotFoundException {
    FileOutputStream fos = new FileOutputStream(archive);
    ZipOutputStream zos = new ZipOutputStream(fos);
    int bytesRead;
    byte[] buffer = new byte[1024];
    CRC32 crc = new CRC32();

    for (File file : files) {
        if (!file.exists()) {
            System.err.println("Skipping: " + file);
            continue;
        }/*from w w  w .  j a v a 2s .  c o m*/
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            crc.reset();
            while ((bytesRead = bis.read(buffer)) != -1) {
                crc.update(buffer, 0, bytesRead);
            }

            bis.close();

            // Reset to beginning of input stream
            bis = new BufferedInputStream(new FileInputStream(file));
            String entryPath = FileHelper.getRelativePath(archive.getParentFile(), file);

            ZipEntry entry = new ZipEntry(entryPath);
            entry.setMethod(ZipEntry.STORED);
            entry.setCompressedSize(file.length());
            entry.setSize(file.length());
            entry.setCrc(crc.getValue());
            zos.putNextEntry(entry);
            while ((bytesRead = bis.read(buffer)) != -1) {
                zos.write(buffer, 0, bytesRead);
            }
        } catch (FileNotFoundException e) {

        } catch (IOException e) {
            e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
        } finally {
            IOUtils.closeQuietly(bis);
        }
    }
    IOUtils.closeQuietly(zos);
    return archive;
}

From source file:de.suse.swamp.util.FileUtils.java

/**
 * Decompress the provided Stream to "targetPath"
 *//* w w w.  j av  a 2  s  .  co  m*/
public static void uncompress(InputStream inputFile, String targetPath) throws Exception {
    ZipInputStream zin = new ZipInputStream(new BufferedInputStream(inputFile));
    BufferedOutputStream dest = null;
    ZipEntry entry;
    while ((entry = zin.getNextEntry()) != null) {
        int count;
        byte data[] = new byte[2048];
        // write the files to the disk
        if (entry.isDirectory()) {
            org.apache.commons.io.FileUtils.forceMkdir(new File(targetPath + "/" + entry.getName()));
        } else {
            FileOutputStream fos = new FileOutputStream(targetPath + "/" + entry.getName());
            dest = new BufferedOutputStream(fos, 2048);
            while ((count = zin.read(data, 0, 2048)) != -1) {
                dest.write(data, 0, count);
            }
            dest.flush();
            dest.close();
        }
    }
}

From source file:JarResources.java

public JarResources(String jarFileName) throws Exception {
    this.jarFileName = jarFileName;
    ZipFile zf = new ZipFile(jarFileName);
    Enumeration e = zf.entries();
    while (e.hasMoreElements()) {
        ZipEntry ze = (ZipEntry) e.nextElement();

        htSizes.put(ze.getName(), new Integer((int) ze.getSize()));
    }/*from  w w w .  jav a2  s.c  o  m*/
    zf.close();

    // extract resources and put them into the hashtable.
    FileInputStream fis = new FileInputStream(jarFileName);
    BufferedInputStream bis = new BufferedInputStream(fis);
    ZipInputStream zis = new ZipInputStream(bis);
    ZipEntry ze = null;
    while ((ze = zis.getNextEntry()) != null) {
        if (ze.isDirectory()) {
            continue;
        }

        int size = (int) ze.getSize();
        // -1 means unknown size.
        if (size == -1) {
            size = ((Integer) htSizes.get(ze.getName())).intValue();
        }

        byte[] b = new byte[(int) size];
        int rb = 0;
        int chunk = 0;
        while (((int) size - rb) > 0) {
            chunk = zis.read(b, rb, (int) size - rb);
            if (chunk == -1) {
                break;
            }
            rb += chunk;
        }

        htJarContents.put(ze.getName(), b);
    }
}

From source file:com.usefullc.platform.common.utils.IOUtils.java

/**
 * /*from  www.j  a  v a  2 s  .  co  m*/
 * 
 * @param path
 * @param fileName
 * @param response
 * @return
 */
public static void download(String path, String fileName, HttpServletResponse response) {
    try {

        if (StringUtils.isEmpty(path)) {
            throw new IllegalArgumentException("?");
        } else {
            File file = new File(path);
            if (!file.exists()) {
                throw new IllegalArgumentException("??");
            }
        }
        if (StringUtils.isEmpty(fileName)) {
            throw new IllegalArgumentException("???");
        }
        if (response == null) {
            throw new IllegalArgumentException("response ?");
        }

        // path
        File file = new File(path);

        // ??
        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // response
        response.reset();

        // ??linux ?  linux utf-8,windows  GBK)
        String defaultEncoding = System.getProperty("file.encoding");
        if (defaultEncoding != null && defaultEncoding.equals("UTF-8")) {

            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("GBK"), "iso-8859-1"));
        } else {
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
        }

        // responseHeader
        response.addHeader("Content-Length", "" + file.length());
        response.setContentType("application/octet-stream");
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.mc.printer.model.utils.ZipHelper.java

public static void unZip(String sourceZip, String outDirName) throws IOException {
    log.info("unzip source:" + sourceZip);
    log.info("unzip to :" + outDirName);
    ZipFile zfile = new ZipFile(sourceZip);
    System.out.println(zfile.getName());
    Enumeration zList = zfile.entries();
    ZipEntry ze = null;/*from w ww . j a va 2 s  . c om*/
    byte[] buf = new byte[1024];
    while (zList.hasMoreElements()) {
        //ZipFileZipEntry
        ze = (ZipEntry) zList.nextElement();
        if (ze.isDirectory()) {
            continue;
        }
        //ZipEntry?InputStreamOutputStream
        File fil = getRealFileName(outDirName, ze.getName());

        OutputStream os = new BufferedOutputStream(new FileOutputStream(fil));
        InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
        int readLen = 0;
        while ((readLen = is.read(buf, 0, 1024)) != -1) {
            os.write(buf, 0, readLen);
        }
        is.close();
        os.close();
        log.debug("Extracted: " + ze.getName());
    }
    zfile.close();

}

From source file:de.thischwa.pmcms.tool.ChecksumTool.java

/**
 * Wrapper to {@link #get(InputStream)}.
 *///from  w ww . jav a  2s.co  m
public static Map<String, String> get(final File checksumXmlFile) {
    try {
        return get(new BufferedInputStream(new FileInputStream(checksumXmlFile)));
    } catch (Exception e) {
        throw new FatalException("Error while reading checksum file: " + e.getMessage(), e);
    }
}

From source file:net.GoTicketing.GetNecessaryCookie.java

public static void getCookie(String host, String referer, String target, Map<String, String> cookieMap) {

    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
        HttpGet httpGet = new HttpGet(host + target);
        httpGet.setConfig(DEFAULT_PARAMS);

        String cookies = CookieMapToString(cookieMap);
        if (!cookies.equals(""))
            httpGet.setHeader("Cookie", cookies);

        httpGet.setHeader("Referer", host + referer);

        try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) {

            //  HttpStatusCode != 200 && != 404
            if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK
                    && httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NOT_FOUND) {
                String ErrorCode = "Response Status : " + httpResponse.getStatusLine().getStatusCode();
                throw new IOException(ErrorCode);
            }/*from   w w  w  .  j  a va 2 s . c o m*/

            try (BufferedInputStream buff = new BufferedInputStream(httpResponse.getEntity().getContent())) {
                String hstr;
                for (Header header : httpResponse.getHeaders("Set-Cookie")) {
                    hstr = header.getValue().split(";")[0];
                    cookieMap.put(hstr.split("=", 2)[0], hstr.split("=", 2)[1]);
                }
            }
        }
    } catch (IOException ex) {
        logger.log(Level.WARNING, "Get cookie from {0} failed in exception : {1}", new Object[] { target, ex });
    }
}

From source file:eu.scape_project.arc2warc.utils.ArcUtils.java

/**
 * Read the ARC record content into a byte array. Note that the record
 * content can be only read once, it is "consumed" afterwards.
 *
 * @param arcRecord ARC record.//ww  w  .j  a va2 s.  c  o  m
 * @return Content byte array.
 * @throws IOException If content is too large to be stored in a byte array.
 */
public static byte[] arcRecordPayloadToByteArray(ARCRecord arcRecord) throws IOException {
    // Byte point where the content of the ARC record begins
    int contentBegin = (int) arcRecord.getMetaData().getContentBegin();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BufferedInputStream buffis = new BufferedInputStream(arcRecord);
    BufferedOutputStream buffos = new BufferedOutputStream(baos);
    byte[] tempBuffer = new byte[BUFFER_SIZE];
    int bytesRead;
    // skip header content
    buffis.skip(contentBegin);
    while ((bytesRead = buffis.read(tempBuffer)) != -1) {
        buffos.write(tempBuffer, 0, bytesRead);
    }
    buffis.close();
    buffos.flush();
    buffos.close();
    return baos.toByteArray();
}

From source file:de.tudarmstadt.lt.utilities.IOUtils.java

public static String read(InputStream is, Charset charset) throws FileNotFoundException, IOException {
    SimpleByteArrayInputStream in = new SimpleByteArrayInputStream(new BufferedInputStream(is));
    byte[] bytes = in.readAll();
    in.close();/*from w  ww  . j a v  a2s  .c o m*/
    String result = stringFromBytes(bytes, charset);
    return result;
}

From source file:com.bdaum.zoom.net.core.internal.Activator.java

public static InputStream openStream(String url, int timeout)
        throws MalformedURLException, IOException, HttpException {
    URL u = new URL(url);
    URLConnection con = u.openConnection();
    con.setConnectTimeout(timeout);/*  w ww.j a  v  a  2s . co  m*/
    con.setReadTimeout(timeout);
    try {
        return new BufferedInputStream(con.getInputStream());
    } catch (IOException e) {
        int responseCode = -1;
        if (con instanceof HttpURLConnection)
            responseCode = ((HttpURLConnection) con).getResponseCode();
        else if (con instanceof HttpsURLConnection)
            responseCode = ((HttpsURLConnection) con).getResponseCode();
        if (responseCode >= 0 && responseCode != HttpStatus.SC_OK)
            throw new HttpException(getStatusText(responseCode), e);
        throw e;
    }
}