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 synchronized int read() throws IOException 

Source Link

Document

See the general contract of the read method of InputStream.

Usage

From source file:com.bjorsond.android.timeline.utilities.Utilities.java

public static File DownloadFromUrl(String imageURL, String fileName) { //this is the downloader method
    try {/*  w  w w . j ava  2s.  com*/
        URL url = new URL(imageURL); //you can write here any link
        File file = new File(fileName);
        System.out.println("THE FILENAME IS " + fileName);
        if (!file.exists()) {
            long startTime = System.currentTimeMillis();
            Log.d("ImageManager", "download begining");
            Log.d("ImageManager", "download url:" + url);
            Log.d("ImageManager", "downloaded file name:" + fileName);
            File downloadFolder = new File(Utilities.getFilePathFromURL(fileName));
            if (!downloadFolder.exists()) {
                downloadFolder.mkdirs();
            }

            /* Open a connection to that URL. */
            URLConnection ucon = url.openConnection();

            /*
            * Define InputStreams to read from the URLConnection.
            */
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

            /*
            * Read bytes to the Buffer until there is nothing more to read(-1).
            */
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }

            /* Convert the Bytes read to a String. */
            FileOutputStream fos = new FileOutputStream(file);

            fos.write(baf.toByteArray());
            fos.close();
            Log.d("ImageManager",
                    "download ready in" + ((System.currentTimeMillis() - startTime) / 1000) + " sec");
        } else {
            Log.d("ImageManager", "file exists!");
        }
        return file;

    } catch (IOException e) {
        Log.d("ImageManager", "Error: " + e);
        return null;
    }

}

From source file:it.geosolutions.geobatch.destination.common.utils.RemoteBrowserUtils.java

/**
 * Download a remote file to a local path
 * /* ww  w .ja v  a 2  s  . c o m*/
 * @param fo
 * @param localPath
 * @return File with the content
 * @throws IOException
 */
public static File downloadFile(FileObject fo, String localPath) throws IOException {

    // open input stream from the remote file
    BufferedInputStream is = null;
    OutputStream os = null;

    try {
        is = new BufferedInputStream(fo.getContent().getInputStream());
        // open output stream to local file
        os = new BufferedOutputStream(new FileOutputStream(localPath));
        int c;
        // do copying
        while ((c = is.read()) != -1) {
            os.write(c);
        }
    } catch (FileSystemException e) {
        throw new IOException("Can't open input stream", e);
    } finally {
        if (os != null) {
            os.close();
        }
        if (is != null) {
            is.close();
        }
    }

    return new File(localPath);
}

From source file:com.uf.togathor.db.couchdb.ConnectionHandler.java

/**
 * Get a File object from an URL/*from   w ww  .  j a v a2 s . c om*/
 * 
 * @param url
 * @param path
 * @return
 * @throws IOException 
 * @throws ClientProtocolException 
 * @throws TogathorException
 * @throws JSONException 
 * @throws IllegalStateException 
 * @throws TogathorForbiddenException
 */
public static void getFile(String url, File file, String userId, String token) throws IOException,
        TogathorException, IllegalStateException, JSONException, TogathorForbiddenException {

    File mFile = file;

    //URL mUrl = new URL(url); // you can write here any link

    InputStream is = httpGetRequest(url, userId);
    BufferedInputStream bis = new BufferedInputStream(is);

    ByteArrayBuffer baf = new ByteArrayBuffer(20000);
    int current = 0;
    while ((current = bis.read()) != -1) {
        baf.append((byte) current);
    }

    /* Convert the Bytes read to a String. */
    FileOutputStream fos = new FileOutputStream(mFile);
    fos.write(baf.toByteArray());
    fos.flush();
    fos.close();
    is.close();

}

From source file:Hash.Hash.java

private static long startOfScanJPG(BufferedInputStream in) throws IOException {
    int c;//w  w  w  . ja  v a 2s  .  c  o m
    long j = startOfImageJPG(in);
    if (j == -1)
        return -1;
    Boolean marker = false;
    while ((c = in.read()) != -1) {
        if (marker)
            //Not a marker(byte stuffing), shouldn't happen in header
            if (c == 0/* || c==216*/)
                marker = false;
            //Start of Quantization table, practically the image
            //Didn't work                else if (c == 219) return j;
            //Start of Scan
            else if (c == 0xDA /*218*/)
                return j;
            else {
                //                    System.out.print("ff" + Integer.toHexString(c) + " ");
                long jump = 256 * in.read() + in.read() - 2;
                //                    System.out.println(Long.toHexString(jump));
                do {
                    long skip = in.skip(jump);
                    if (skip < 0)
                        return -1;
                    jump -= skip;
                } while (jump > 0);
                j += jump + 2;
                marker = false;
            }
        else {
            if (c == 0xFF/*255*/) {
                marker = true;
                //                } else if (c == 0) {//byte stuffing
            } else {
                return -1;
            }
        }
        j++;
    }
    return -1;
}

From source file:com.bristle.javalib.io.FileUtil.java

/**************************************************************************
* Skip past all bytes in the specified InputStream, returning the count
* of bytes found./*from  w  w  w. j  av  a 2  s  . com*/
*@param  streamIn       InputStream to read from
*@return                Count of bytes found in the stream.
*@throws IOException    When an I/O error occurs reading or writing a
*                       stream.
**************************************************************************/
public static long skipEntireStreamReturningCount(InputStream streamIn) throws IOException {
    // Buffer the input and output for efficiency, to avoid lots of 
    // small I/O operations.
    // Note: Don't call the read() and write() methods that could do it 
    //       all in a single byte-array because we don't want to consume 
    //       that caller-specified amount of memory.  Better to do it
    //       one byte at a time, but with buffering for efficiency.
    BufferedInputStream buffIn = new BufferedInputStream(streamIn);

    long lngCount = 0;
    for (int intByte = buffIn.read(); intByte > -1; intByte = buffIn.read()) {
        lngCount++;
    }
    return lngCount;
}

From source file:de.nrw.hbz.deepzoomer.fileUtil.FileUtil.java

/**
 * <p><em>Title: Create a temporary File from a file identified by URL</em></p>
 * <p>Description: Method creates a temporary file from a remote file addressed 
 * an by URL representing the orginal PDF, that should be converted</p>
 * //from   w  ww  .j  a  va 2 s.  c om
 * @param fileName
 * @param url
 * @return 
 */
public static String saveUrlToFile(String fileName, String url) {
    File inputFile = new File(Configuration.getTempDirPath() + "/" + fileName);
    log.debug(inputFile.getAbsolutePath());
    InputStream is = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;

    log.info(url);
    try {
        URL inputDocument = new URL(url);
        is = inputDocument.openStream();
        bis = new BufferedInputStream(is);

        fos = new FileOutputStream(inputFile);
        bos = new BufferedOutputStream(fos);
        int i = -1;
        while ((i = bis.read()) != -1) {
            bos.write(i);
        }
        bos.flush();
    } catch (Exception e) {
        log.error(e);
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
    }
    return inputFile.getName();
}

From source file:br.com.capanema.kers.velocity.util.BuildManagerUtil.java

/**
 * Increment source code of filePath using template fragment.
 * // w  w  w .j  a  va 2 s . c  o  m
 * @param filePath
 * @param incrementPath
 * @param incrementPattern
 * @param dataGroup
 */
public static void incrementSourceCode(String filePath, String incrementPath, String incrementPattern,
        String firstAfter, Map<String, String> params, TemplateDataGroup dataGroup) {
    try {
        HashMap<String, Object> velocityVariables = new HashMap<String, Object>(); //map for velocity variables
        velocityVariables.put("data", dataGroup); //conjunto de vriaveis que podem ser usados no template

        if (params != null && params.size() > 0) {
            /*            for (String name : params.keySet()) {
                           velocityVariables.put("params."+name, params.get(name));
                        }*/
            velocityVariables.put("params", params);
        }

        //rodando velocity do incremento
        TemplateEngine templateEngine = TemplateEngineFactory.getEngine(incrementPath, true);
        String incrementSource = templateEngine.runFile(incrementPath, velocityVariables);

        // Create the pattern
        Pattern pattern = Pattern.compile("[\r\n]*[\t]*" + incrementPattern, Pattern.DOTALL); //o "[\r\n]*"  para pegar as quebras de linhas que podem existir no incremento
        Matcher matcher = pattern.matcher("");

        //novo incremento
        //aqui vai executar o pattern no prprio incremento... se o pattern estiver errado no ir encontrar nada e vai abortar o incremento
        matcher.reset(incrementSource);
        Map<String, String[]> mapGroupIncrement = new LinkedHashMap<String, String[]>();
        while (matcher.find()) {
            String[] groups = new String[matcher.groupCount()];
            for (int i = 0; i < matcher.groupCount(); i++) {
                groups[i] = matcher.group(i + 1);
            }

            String increment = matcher.group(); //new increment
            mapGroupIncrement.put(increment, groups); //map increment vs groups
        }

        if (mapGroupIncrement.size() == 0) { //no encontrou groups no incremento (usado para as comparaes), aborta
            return;
        }

        //le o arquivo atual
        FileInputStream inputFilePath = new FileInputStream(filePath);
        BufferedInputStream bufferedInput = new BufferedInputStream(inputFilePath);
        StringBuffer filePathContent = new StringBuffer();
        int ch = 0;
        while ((ch = bufferedInput.read()) > -1) {
            filePathContent.append((char) ch);
        }
        inputFilePath.close();
        bufferedInput.close();

        //procura no arquivo todo pela expresso regular
        matcher = pattern.matcher("");
        matcher.reset(filePathContent);
        StringBuffer newContentFile = new StringBuffer();
        int countMatcher = 0;
        Map<String, String[]> mapGroupFile = new HashMap<String, String[]>();
        while (matcher.find()) { //verifica cada ocorrncia da expresso no arquivo
            String[] groups = new String[matcher.groupCount()]; //pega os groups "()" do matcher para fazer a comparao com os groups do incremento que est sendo gerado
            for (int i = 0; i < matcher.groupCount(); i++) {
                groups[i] = matcher.group(i + 1);
            }
            mapGroupFile.put(matcher.group(), groups); //adiciona esse group em uma lista para ser avaliado depois

            countMatcher++; //isso vai contar onde esta o ltimo matcher
        }

        //valida quais incrementos so realmente novos, comparando os groups
        List<String> newIncrements = new LinkedList<String>();
        for (String groupIncrement : mapGroupIncrement.keySet()) {
            String[] groups1 = mapGroupIncrement.get(groupIncrement); //groups do incremento
            boolean itemFound = false;

            for (String groupFile : mapGroupFile.keySet()) {
                String[] groups2 = mapGroupFile.get(groupFile); //groups do incremento

                if (ArrayUtil.equals(groups1, groups2)) { //se no arquivo tem o cdigo que est sendo gerado, no precisa adicionar esse incremnto
                    itemFound = true;
                }
            }
            if (!itemFound) { //se no arquivo no tem o cdigo que est sendo gerado, adiciona em um array
                newIncrements.add(groupIncrement);
            }
        }

        //realiza uma quebra de linha adicional para o primeiro item do incremento, para no ficar na mesma linha do ltimo matcher no arquivo
        StringBuffer newIncrementSource = new StringBuffer();
        int i = 0;
        for (String incremento : newIncrements) {
            if (i == 0 && incremento.indexOf("\r\n\r\n") != 0) { //s coloca quebra de linha se precisar
                newIncrementSource.append("\r\n");
            }

            newIncrementSource.append(incremento);
            i++;
        }

        if (newIncrements.size() > 0) {
            //no encontrou nenhum increment no arquivo, ento procura pelo firstAfter para inserir o primeiro incremento
            if (countMatcher == 0 && firstAfter != null && !firstAfter.equals("")) {
                pattern = Pattern.compile(firstAfter, Pattern.DOTALL);
                matcher = pattern.matcher("");
                matcher.reset(filePathContent);

                //esse loop s serviu para contar e achar o ltimo matcher. No consegui fazer sem isso :(
                countMatcher = 0;
                while (matcher.find()) { //verifica cada ocorrncia da expresso
                    countMatcher++;
                }
            }

            //aqui vou realmente substituir os valores, j sabendo qual  a ltima ocorrencia da palavra no arquivo
            i = 0;
            matcher.reset();
            while (matcher.find()) { //verifica cada ocorrncia da expresso
                i++;
                if (countMatcher == i) { //se encontrou a ltima ocorrencia
                    String matcherGroup = matcher.group();
                    matcher.appendReplacement(newContentFile, matcherGroup + newIncrementSource); //substitui a ultima ocorrencia do firstIncrement   
                }
            }
            matcher.appendTail(newContentFile);
        }

        //save new file
        if (newContentFile.length() > 0) {
            FileUtil.writeFile(filePath, newContentFile.toString());
        }
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
}

From source file:de.uzk.hki.da.sb.restfulService.FileUtil.java

/**
 * <p><em>Title: Create a temporary File from a file identified by URL</em></p>
 * <p>Description: Method creates a temporary file from a remote file addressed 
 * an by URL representing the orginal PDF, that should be converted</p>
 * /* w ww . j  a v a 2  s.co  m*/
 * @param fileName
 * @param url
 * @return 
 */
public static String saveUrlToFile(String fileName, String url) {

    String path = fileName.substring(0, fileName.lastIndexOf("/"));
    File dir = new File(Configuration.getTempDirPath() + "/" + path);
    dir.mkdirs();

    File inputFile = new File(Configuration.getTempDirPath() + "/" + fileName);
    InputStream is = null;
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;

    log.info(url);
    try {
        URL inputDocument = new URL(url);
        is = inputDocument.openStream();
        bis = new BufferedInputStream(is);

        fos = new FileOutputStream(inputFile);
        bos = new BufferedOutputStream(fos);
        int i = -1;
        while ((i = bis.read()) != -1) {
            bos.write(i);
        }
        bos.flush();
    } catch (Exception e) {
        log.error(e);
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioExc) {
                log.error(ioExc);
            }
        }
    }

    return inputFile.getAbsolutePath();
}

From source file:com.depas.utils.FileUtils.java

/**
 * Returns content of resource that exists on classpath
 *//*  w  ww  . j a  v  a  2s  . co  m*/
public static String getTextFromResource(String resourceName) throws IOException {

    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    if (cl.getResource(resourceName) == null) {
        throw new FileNotFoundException(
                "The resource " + resourceName + " could not be found on the current classpath.");
    }

    StringBuffer buf = new StringBuffer();
    BufferedInputStream bis = null;
    try {
        InputStream is = cl.getResourceAsStream(resourceName);
        bis = new BufferedInputStream(is);

        int i;
        while ((i = bis.read()) != -1) {
            buf.append((char) i);
        }
    } finally {
        try {
            bis.close();
        } catch (Exception ex) {
        }
    }

    return buf.toString();

}

From source file:com.bristle.javalib.io.FileUtil.java

/**************************************************************************
* Copy the binary contents of the specified InputStream to the specified
* Writer, up to the specified number of bytes, returning the count of 
* bytes written./*from w ww . j  av  a 2s  .co m*/
*@param  streamIn       InputStream to read from
*@param  writerOut      Writer to write to
*@param  lngMaxBytes    Max number of bytes to copy, or lngNO_MAX_BYTES
*                       for unlimited
*@return                Count of bytes written
*@throws TooManyBytesException
*                       When streamIn contains more than intMaxBytes,
*                       resulting in a partially copied binary stream.
*@throws IOException    When an I/O error occurs reading or writing a
*                       stream or Writer.
**************************************************************************/
public static long copyBinaryStreamToWriter(InputStream streamIn, Writer writerOut, long lngMaxBytes)
        throws TooManyBytesException, IOException {
    // Note: It seems as though this method should be able to call 
    //       copyBinaryStreamToStream() instead of being a nearly 
    //       identical copy of the code, but how to convert a Writer 
    //       to an OutputStream to pass to copyBinaryStreamToStream()?

    // Buffer the input and output for efficiency, to avoid lots of 
    // small I/O operations.
    // Note: Don't call the read() and write() methods that could do it 
    //       all in a single byte-array because we don't want to consume 
    //       that caller-specified amount of memory.  Better to do it
    //       one byte at a time, but with buffering for efficiency.
    BufferedInputStream buffIn = new BufferedInputStream(streamIn);
    BufferedWriter buffOut = new BufferedWriter(writerOut);

    long lngBytesWritten = 0;
    for (int intByte = buffIn.read(); intByte > -1; intByte = buffIn.read()) {
        if (lngMaxBytes != lngNO_MAX_BYTES && lngBytesWritten >= lngMaxBytes) {
            buffOut.flush();
            throw new TooManyBytesException("The input stream contains more than " + lngMaxBytes
                    + " bytes.  Only " + lngBytesWritten + " bytes were written to the " + "writer",
                    lngBytesWritten);
        }
        buffOut.write(intByte);
        lngBytesWritten++;
    }
    buffOut.flush();
    return lngBytesWritten;
}