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:cc.twittertools.corpus.data.TarJsonStatusCorpusReader.java

public TarJsonStatusCorpusReader(File file) throws IOException {
    Preconditions.checkNotNull(file);//  w  ww .ja v a 2 s.c  o m

    if (!file.isFile()) {
        throw new IOException("Expecting " + file + " to be a file!");
    }

    tarInput = new TarArchiveInputStream(new BufferedInputStream(new FileInputStream(file)));
}

From source file:cn.edu.zju.acm.onlinejudge.util.ProblemManager.java

public static ProblemPackage importProblem(InputStream in, ActionMessages messages) {

    Map<String, byte[]> files = new HashMap<String, byte[]>();
    ZipInputStream zis = null;/* w  ww  .j  av a 2 s. c o  m*/
    try {

        zis = new ZipInputStream(new BufferedInputStream(in));
        // zis = new ZipInputStream(new BufferedInputStream(new FileInputStream("d:/100.zip")));
        ZipEntry entry = zis.getNextEntry();
        while (entry != null) {
            if (!entry.isDirectory()) {

                // TODO the file may be too big. > 100M
                /*
                 * byte data[] = new byte[(int) entry.getSize()]; int l = 0; while (l < data.length) { int ll =
                 * zis.read(data, l, data.length - l); if (ll < 0) { break; } l += ll; }
                 */
                ByteArrayOutputStream buf = new ByteArrayOutputStream();
                CopyUtils.copy(zis, buf);
                files.put(entry.getName(), buf.toByteArray());

            }
            entry = zis.getNextEntry();
        }

    } catch (IOException ioe) {
        messages.add("error", new ActionMessage("onlinejudge.importProblem.invalidzip"));
        return null;
    } finally {
        try {
            if (zis != null) {
                zis.close();
            }
        } catch (IOException e) {
            // ignore
        }
    }
    /*
     * files.clear(); files.put("problems.csv", "3,a\n2,b,true,1,2,3,4,a,b,c\n1,c".getBytes());
     * files.put("1\\checker", "checker".getBytes()); files.put("1\\input", "input".getBytes());
     * files.put("1\\output", "output".getBytes()); files.put("3\\checker", "checker3".getBytes());
     * files.put("3\\input", "input3".getBytes()); files.put("3\\output", "output3".getBytes());
     * files.put("images\\1.jpg", "1".getBytes()); files.put("images\\2\\2.jpg", "2".getBytes());
     */
    if (!files.containsKey(ProblemManager.PROBLEM_CSV_FILE)) {
        messages.add("error", new ActionMessage("onlinejudge.importProblem.missingproblemscsv"));
        return null;
    }
    ProblemPackage problemPackage = ProblemManager.parse(files, messages);
    if (messages.size() > 0) {
        return null;
    }
    return problemPackage;
}

From source file:com.roche.iceboar.cachestorage.LocalCacheStorage.java

public CacheStatus loadCacheStatus(String cachePath) {
    InputStream file = null;//from  w  ww. j  a  va 2  s . c  o  m
    InputStream buffer = null;
    ObjectInput input = null;
    try {
        file = new FileInputStream(cachePath);
        buffer = new BufferedInputStream(file);
        input = new ObjectInputStream(buffer);

        CacheStatus cacheStatus = (CacheStatus) input.readObject();
        return cacheStatus;
    } catch (Exception e) {
        System.out.println("Can't open file with cache settings. Expected file here: " + cachePath);
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (buffer != null) {
            try {
                buffer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (file != null) {
            try {
                file.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return new CacheStatus();
}

From source file:CharsetDetector.java

private Charset detectCharset(File f, Charset charset) {
    try {// ww w.  j a v a2s .c o  m
        BufferedInputStream input = new BufferedInputStream(new FileInputStream(f));

        CharsetDecoder decoder = charset.newDecoder();
        decoder.reset();

        byte[] buffer = new byte[512];
        boolean identified = false;
        while ((input.read(buffer) != -1) && (!identified)) {
            identified = identify(buffer, decoder);
        }

        input.close();

        if (identified) {
            return charset;
        } else {
            return null;
        }

    } catch (Exception e) {
        return null;
    }
}

From source file:cn.guoyukun.spring.web.utils.DownloadUtils.java

public static void download(HttpServletRequest request, HttpServletResponse response, String filePath,
        String displayName) throws IOException {
    File file = new File(filePath);

    if (StringUtils.isEmpty(displayName)) {
        displayName = file.getName();//from   www .j  av  a 2s.  c  o m
    }

    if (!file.exists() || !file.canRead()) {
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write("??");
        return;
    }

    String userAgent = request.getHeader("User-Agent");
    boolean isIE = (userAgent != null) && (userAgent.toLowerCase().indexOf("msie") != -1);

    response.reset();
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "must-revalidate, no-transform");
    response.setDateHeader("Expires", 0L);

    response.setContentType("application/x-download");
    response.setContentLength((int) file.length());

    String displayFilename = displayName.substring(displayName.lastIndexOf("_") + 1);
    displayFilename = displayFilename.replace(" ", "_");
    if (isIE) {
        displayFilename = URLEncoder.encode(displayFilename, "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=\"" + displayFilename + "\"");
    } else {
        displayFilename = new String(displayFilename.getBytes("UTF-8"), "ISO8859-1");
        response.setHeader("Content-Disposition", "attachment;filename=" + displayFilename);
    }
    BufferedInputStream is = null;
    OutputStream os = null;
    try {

        os = response.getOutputStream();
        is = new BufferedInputStream(new FileInputStream(file));
        IOUtils.copy(is, os);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:c3.ops.priam.compress.SnappyCompression.java

private void decompress(InputStream input, OutputStream output) throws IOException {
    SnappyInputStream is = new SnappyInputStream(new BufferedInputStream(input));
    byte data[] = new byte[BUFFER];
    BufferedOutputStream dest1 = new BufferedOutputStream(output, BUFFER);
    try {//  w ww. j a  v a  2  s  .c  o m
        int c;
        while ((c = is.read(data, 0, BUFFER)) != -1) {
            dest1.write(data, 0, c);
        }
    } finally {
        IOUtils.closeQuietly(dest1);
        IOUtils.closeQuietly(is);
    }
}

From source file:ch.entwine.weblounge.common.impl.content.image.ImageMetadataUtils.java

/**
 * This utility method extracts image metadata stored in EXIF and IPTC tags
 * and returns the extracted information in a {@link ImageMetadata}.
 * //w w  w .j  av  a 2 s.  c om
 * @param img
 *          image file
 * @return extracted meta information
 */
public static ImageMetadata extractMetadata(File img) {
    BufferedInputStream is = null;
    try {
        is = new BufferedInputStream(new FileInputStream(img));
        return extractMetadata(is);
    } catch (FileNotFoundException e) {
        logger.warn("Tried to extract image metadata from none existing file '{}'", img.getName());
        return null;
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.creditease.utilframe.http.client.entity.FileUploadEntity.java

@SuppressWarnings("resource")
@Override/*ww  w  .j av  a2  s  .com*/
public void writeTo(OutputStream outStream) throws IOException {
    if (outStream == null) {
        throw new IllegalArgumentException("Output stream may not be null");
    }
    BufferedInputStream inStream = null;
    try {
        inStream = new BufferedInputStream(new FileInputStream(this.file));
        byte[] tmp = new byte[4096];
        int len;
        while ((len = inStream.read(tmp)) != -1) {
            outStream.write(tmp, 0, len);
            uploadedSize += len;
            if (callBackHandler != null) {
                if (!callBackHandler.updateProgress(fileSize, uploadedSize, false)) {
                    IOUtils.closeQuietly(inStream);
                    throw new InterruptedIOException("cancel");
                }
            }
        }
        outStream.flush();
        if (callBackHandler != null) {
            callBackHandler.updateProgress(fileSize, uploadedSize, true);
        }
    } finally {
        IOUtils.closeQuietly(inStream);
    }
}

From source file:com.progressiveaccess.cmlspeech.base.FileHandler.java

/**
 * Loads current file into the molecule IAtomContainer.
 *
 * @param fileName//from   www  .j  av a2  s .  c o  m
 *          File to load.
 *
 * @return The molecule loaded.
 *
 * @throws IOException
 *           Problems with loading file.
 * @throws CDKException
 *           Problems with input file format.
 */
public static IAtomContainer readFile(final String fileName) throws IOException, CDKException {
    final InputStream file = new BufferedInputStream(new FileInputStream(fileName));
    final ISimpleChemObjectReader reader = new ReaderFactory().createReader(file);
    IChemFile cmlFile = null;
    cmlFile = reader.read(SilentChemObjectBuilder.getInstance().newInstance(IChemFile.class));
    reader.close();
    final IAtomContainer molecule = ChemFileManipulator.getAllAtomContainers(cmlFile).get(0);
    Logger.logging(molecule);
    return molecule;
}

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

public static boolean isTextData(FileSystem fs, Path p) {
    try {// w w  w  .  j  ava2 s.co  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;
    }
}