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:org.alfresco.selenium.FetchUtil.java

/**
 * Retrieve file with authentication, using {@link WebDriver} cookie we
 * keep the session and use HttpClient to download files that requires
 * user to be authenticated. /*from   ww w  . j av a 2 s.  c  o  m*/
 * @param resourceUrl path to file to download
 * @param driver {@link WebDriver}
 * @param output path to output the file
 * @throws IOException if error
 */
protected static File retrieveFile(final String resourceUrl, final CloseableHttpClient client,
        final File output) throws IOException {
    HttpGet httpGet = new HttpGet(resourceUrl);
    BufferedOutputStream bos = null;
    BufferedInputStream bis = null;
    HttpResponse response = null;
    try {
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        bos = new BufferedOutputStream(new FileOutputStream(output));
        bis = new BufferedInputStream(entity.getContent());
        int inByte;
        while ((inByte = bis.read()) != -1)
            bos.write(inByte);
        HttpClientUtils.closeQuietly(response);
    } catch (Exception e) {
        logger.error("Unable to fetch file " + resourceUrl, e);
    } finally {
        if (response != null) {
            HttpClientUtils.closeQuietly(response);
        }
        if (bis != null) {
            bis.close();
        }
        if (bos != null) {
            bos.close();
        }
    }
    return output;
}

From source file:de.rub.syssec.saaf.misc.ByteUtils.java

/**
 * Read a line from an inputstream into a byte buffer. A line might end with a LF or an CRLF. CR's are accepted inside a line and
 * are not understood as a beginning new line. This should work therefore on Mac OS X, Unix, Linux and Windows.
 * /* ww  w .  j  a  v a2 s.  c o  m*/
 * See http://en.wikipedia.org/wiki/Newline for more.
 *  
 * @param in the inputstream
 * @param maxSize the maximum amount of bytes to read until a CRLF or LF is reached, a value of zero or smaller disables a limit (use w/ care!)
 * @return the buffer where read bytes are appended, this buffer will not contain any CR's or or CRLF's at the end of the array. Null is
 * returned if EOF is reached.
 * @throws IOException if something is wrong w/ the stream or the maxSize is reached
 */
public static byte[] parseLine(BufferedInputStream in, int maxSize) throws IOException {
    ByteArrayBuffer bab = new ByteArrayBuffer(512);
    int b;
    while (true) {
        if (!(maxSize <= 0 || bab.length() <= maxSize)) {
            throw new IOException("Maximal bytearraybuffer size of " + maxSize + " exceeded!");
        }
        b = in.read();
        if (b == -1) {
            if (bab.isEmpty()) {
                // we have nothing read yet and could nothing read, we will therefore return 'null' as this
                // indicates EOF.
                return null;
            } else {
                // return what we got so far
                return bab.toByteArray();
            }
        }
        // CRLF case
        if (b == '\r') { // check if we find a \n
            int next = in.read();
            if (b == -1) {
                // EOF; return what we got
                return bab.toByteArray();
            } else if (next == '\n') { // we did
                in.mark(-1); // rest mark
                return bab.toByteArray(); // return the line without CRLF
            } else {
                // found no CRLF but only a CR and some other byte, so we need to add both to the buffer and proceed
                bab.append('\r');
                bab.append(b);
            }
        }
        // LF case
        else if (b == '\n') { // we found a LF and therefore the end of a line
            return bab.toByteArray();
        } else { // we just found a byte which is happily appended
            bab.append(b);
        }
    }
}

From source file:Hash.Hash.java

private static long startOfImageJPG(BufferedInputStream in) throws IOException {
    int c;/*from www.  j  av  a2 s .c o m*/
    long j = 0;
    OUTER: while ((c = in.read()) != -1) {
        j++;
        switch (c) {
        case 0:
            break;
        case 0xFF://255
            c = in.read();
            j++;
            if (c == 0xD8 /*216*/) {
                break OUTER;
            }
        default:
            return -1;
        }
    }
    return j;
}

From source file:com.panet.imeta.job.entries.getpop.JobEntryGetPOP.java

public static void saveFile(String foldername, String filename, InputStream input) throws IOException {

    // LogWriter log = LogWriter.getInstance();

    if (filename == null) {
        filename = File.createTempFile("xx", ".out").getName(); //$NON-NLS-1$ //$NON-NLS-2$
    }//w w  w .  j  a v  a2  s . c  om
    // Do no overwrite existing file
    File file = new File(foldername, filename);
    for (int i = 0; file.exists(); i++) {
        file = new File(foldername, filename + i);
    }
    FileOutputStream fos = new FileOutputStream(file);
    BufferedOutputStream bos = new BufferedOutputStream(fos);

    BufferedInputStream bis = new BufferedInputStream(input);
    int aByte;
    while ((aByte = bis.read()) != -1) {
        bos.write(aByte);
    }

    bos.flush();
    bos.close();
    bis.close();
}

From source file:com.jaspersoft.jasperserver.rest.RESTUtils.java

public static void sendFile(DataSource ds, HttpServletResponse response) {
    response.setContentType(ds.getContentType());

    if (ds.getName() != null && ds.getName().length() > 0) {
        response.addHeader("Content-Disposition", "attachment; filename=" + ds.getName());
    }//from   w  w  w.  j  a v  a 2 s.  co  m

    OutputStream outputStream = null;
    BufferedInputStream bufferedInputStream = null;
    try {
        outputStream = response.getOutputStream();

        bufferedInputStream = new BufferedInputStream(ds.getInputStream());
        int readBytes = 0;

        while ((readBytes = bufferedInputStream.read()) != -1) {
            outputStream.write(readBytes);
        }

        if (log.isDebugEnabled()) {
            log.debug("finished sending bytes");
        }

    } catch (IOException ex) {
        log.error("Error serving a file: " + ex.getMessage(), ex);
    } finally {
        if (outputStream != null)
            try {
                outputStream.close();
            } catch (Exception ex) {
            }
        if (bufferedInputStream != null)
            try {
                bufferedInputStream.close();
            } catch (Exception ex) {
            }
    }
}

From source file:net.vexelon.bgrates.Utils.java

/**
 * Downloads a file given URL to specified destination
 * @param url/*w ww  .  j  a va 2s  .c om*/
 * @param destFile
 * @return
 */
//public static boolean downloadFile(Context context, String url, String destFile) {
public static boolean downloadFile(Context context, String url, File destFile) {
    //Log.v(TAG, "@downloadFile()");
    //Log.d(TAG, "Downloading " + url);

    boolean ret = false;

    BufferedInputStream bis = null;
    FileOutputStream fos = null;
    InputStream is = null;

    try {
        URL myUrl = new URL(url);
        URLConnection connection = myUrl.openConnection();

        is = connection.getInputStream();
        bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(1024);

        int n = 0;
        while ((n = bis.read()) != -1)
            baf.append((byte) n);

        // save to internal storage
        //Log.v(TAG, "Saving downloaded file ...");
        fos = new FileOutputStream(destFile);
        //context.openFileOutput(destFile, context.MODE_PRIVATE);
        fos.write(baf.toByteArray());
        fos.close();
        //Log.v(TAG, "File saved successfully.");

        ret = true;
    } catch (Exception e) {
        //Log.e(TAG, "Error while downloading and saving file !", e);
    } finally {
        try {
            if (fos != null)
                fos.close();
        } catch (IOException e) {
        }
        try {
            if (bis != null)
                bis.close();
        } catch (IOException e) {
        }
        try {
            if (is != null)
                is.close();
        } catch (IOException e) {
        }
    }

    return ret;
}

From source file:Hash.Hash.java

private static byte[] startOfScanTiff(File file, BufferedInputStream in) throws IOException {
    in.mark(0);//from ww w . ja v a2 s.  co m
    int c;
    long j = 0;
    Boolean endian = null;
    c = in.read();
    if (c == 73) {
        if (in.read() == 73)
            endian = true;
    } else if (c == 77) {
        if (in.read() == 77)
            endian = false;
    }
    if (endian == null) {
        return null;
    }
    long tiffCheck = readEndianValue(in, 2, endian);
    if (tiffCheck != 42) {
        return null;
    }
    ifdCursor cursor = new ifdCursor(file, endian, readEndianValue(in, 4, endian));
    if (cursor.getPointer() == -1) {
        return null;
    }
    if (cursor.getPointer() == 0) {
        return null;
    }
    return readIFDirectory(cursor, in);
}

From source file:com.cloverstudio.spikademo.couchdb.ConnectionHandler.java

/**
 * Get a File object from an URL//w  ww.  j a v  a  2s  .c  om
 * 
 * @param url
 * @param path
 * @return
 */
public static void getFile(String url, File file, String userId, String token) {

    File mFile = file;

    try {

        //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();

    } catch (Exception e) {
        Logger.error(TAG + "getFile", "Error retrieving file: ", e);
    }

}

From source file:fr.paris.lutece.plugins.upload.web.UploadJspBean.java

/**
 * Copies data from an input stream to an output stream.
 * @param inStream The input stream/*from  w  ww. ja  va  2 s. c om*/
 * @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 = 0;

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

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

From source file:com.aurel.track.util.emailHandling.MailReader.java

/**
 * Saves attachment/*from w  ww .j av a 2  s . co m*/
 */
public static File saveFile(String filename, InputStream input) throws IOException {
    // in case there is no filename, create temporary file and use its
    // filename instead
    String tempDir = HandleHome.getTrackplus_Home() + File.separator + HandleHome.DATA_DIR + File.separator
            + "temp";
    File dirTem = new File(tempDir);
    if (!dirTem.exists()) {
        dirTem.mkdirs();
    }
    File file;
    if (filename == null) {
        file = File.createTempFile("xxxxxx", ".out", dirTem);
    } else {
        // Existing files will not be overwritten
        file = new File(dirTem, filename);
    }

    int i = 0;
    while (file.exists()) {
        // Extend filename by number so it is unique
        file = new File(dirTem, i + filename);
        i++;
    }

    // BufferedOutputStream for writing into the file
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));

    // BufferedInputStream for reading the parts
    BufferedInputStream bis = new BufferedInputStream(input);

    // read data and write to output stream
    int aByte;
    while ((aByte = bis.read()) != -1) {
        bos.write(aByte);
    }

    // release resources
    bos.flush();
    bos.close();
    bis.close();
    return file;
}