Example usage for java.io ByteArrayOutputStream write

List of usage examples for java.io ByteArrayOutputStream write

Introduction

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

Prototype

public synchronized void write(byte b[], int off, int len) 

Source Link

Document

Writes len bytes from the specified byte array starting at offset off to this ByteArrayOutputStream .

Usage

From source file:Main.java

static byte[] streamToBytes(InputStream paramInputStream) throws IOException {
    ByteArrayOutputStream localByteArrayOutputStream = new ByteArrayOutputStream();
    if (paramInputStream != null) {
        byte[] arrayOfByte = new byte[4096];
        while (true) {
            int i = paramInputStream.read(arrayOfByte);
            if (i == -1)
                break;
            localByteArrayOutputStream.write(arrayOfByte, 0, i);
        }//from w w  w. j av a  2  s  .  c o  m
    }
    return localByteArrayOutputStream.toByteArray();
}

From source file:com.syncthemall.enml4j.util.Utils.java

/**
 * Encode an {@code InputStream} representing a file in base64.
 * //from  w  w w. j av  a  2 s. c o  m
 * @param is the source to encode
 * @return a {@code String} representation of the {@code InputStream} in parameter, encoded in base64
 * @throws IOException if an I/O error occurs reading the {@code InputStream} in parameter
 */
public static String encodeToBase64Binary(final InputStream is) throws IOException {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int nRead;
    byte[] data = new byte[BUFFER_SIZE];

    while ((nRead = is.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }
    buffer.flush();

    return Base64.encodeBase64String(buffer.toByteArray());

}

From source file:Main.java

protected static ByteArrayOutputStream inflate(final ByteArrayOutputStream pOutCompressed) throws IOException {
    final ByteArrayOutputStream uncompressed = new ByteArrayOutputStream(ONE_MB);
    final GZIPInputStream zin = new GZIPInputStream(new ByteArrayInputStream(pOutCompressed.toByteArray()));

    int read;//from   w  ww.  ja  va  2s . co m
    final byte[] buf = new byte[ONE_MB];
    while ((read = zin.read(buf)) != -1) {
        uncompressed.write(buf, 0, read);
    }

    return uncompressed;
}

From source file:com.goldmansachs.kata2go.tools.utils.TarGz.java

public static void decompressFromStream2(InputStream inputStream) throws IOException {
    GzipCompressorInputStream gzipStream = new GzipCompressorInputStream(inputStream);
    TarArchiveInputStream tarInput = new TarArchiveInputStream(gzipStream);
    TarArchiveEntry entry;/*from w ww.  j  a va2 s.  co m*/
    int bufferSize = 1024;
    while ((entry = (TarArchiveEntry) tarInput.getNextEntry()) != null) {
        String entryName = entry.getName();
        // strip out the leading directory like the --strip tar argument
        String entryNameWithoutLeadingDir = entryName.substring(entryName.indexOf("/") + 1);
        if (entryNameWithoutLeadingDir.isEmpty()) {
            continue;
        }
        if (entry.isDirectory()) {
            System.out.println("found dir " + entry.getName());
        } else {
            int count;
            byte data[] = new byte[bufferSize];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            while ((count = tarInput.read(data, 0, bufferSize)) != -1) {
                baos.write(data, 0, count);
            }
            JarOutputStream jarOutputStream = new JarOutputStream(baos);
            System.out.println(new String(baos.toByteArray()));
        }
    }
    tarInput.close();
    gzipStream.close();
}

From source file:app.nichepro.fragmenttab.account.AbstractGetNameTask.java

/**
 * Reads the response from the input stream and returns it as a string.
 *///from  w  w  w.j  av  a2 s.c om
private static String readResponse(InputStream is) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] data = new byte[2048];
    int len = 0;
    while ((len = is.read(data, 0, data.length)) >= 0) {
        bos.write(data, 0, len);
    }
    return new String(bos.toByteArray(), "UTF-8");
}

From source file:Main.java

/**
 * Uncompresses a GZIP file.//from  w ww.j a  v a 2s .co  m
 * 
 * @param bytes
 *            The compressed bytes.
 * @return The uncompressed bytes.
 * @throws IOException
 *             if an I/O error occurs.
 */
public static byte[] gunzip(byte[] bytes) throws IOException {
    /* create the streams */
    InputStream is = new GZIPInputStream(new ByteArrayInputStream(bytes));
    try {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            /* copy data between the streams */
            byte[] buf = new byte[4096];
            int len = 0;
            while ((len = is.read(buf, 0, buf.length)) != -1) {
                os.write(buf, 0, len);
            }
        } finally {
            os.close();
        }

        /* return the uncompressed bytes */
        return os.toByteArray();
    } finally {
        is.close();
    }
}

From source file:com.baidu.api.client.core.DownloadUtil.java

/**
 * Download the file pointed by the url and return the content as byte array.
 *
 * @param strUrl         The Url to be downloaded.
 * @param connectTimeout Connect timeout in milliseconds.
 * @param readTimeout    Read timeout in milliseconds.
 * @param maxFileSize    Max file size in BYTE.
 * @return The file content as byte array.
 *//*from  www . ja va2s .  c o m*/
public static byte[] downloadFile(String strUrl, int connectTimeout, int readTimeout, int maxFileSize) {
    InputStream in = null;
    try {
        URL url = new URL(strUrl); // URL?
        URLConnection ucon = url.openConnection();
        ucon.setConnectTimeout(connectTimeout);
        ucon.setReadTimeout(readTimeout);
        ucon.connect();
        if (ucon.getContentLength() > maxFileSize) {
            String msg = "File " + strUrl + " size [" + ucon.getContentLength()
                    + "] too large, download stoped.";
            throw new ClientInternalException(msg);
        }
        if (ucon instanceof HttpURLConnection) {
            HttpURLConnection httpCon = (HttpURLConnection) ucon;
            if (httpCon.getResponseCode() > 399) {
                String msg = "Failed to download file " + strUrl + " server response "
                        + httpCon.getResponseMessage();
                throw new ClientInternalException(msg);
            }
        }
        in = ucon.getInputStream(); // ?
        byte[] byteBuf = new byte[BUFFER_SIZE];
        byte[] ret = null;
        int count, total = 0;
        // ??
        while ((count = in.read(byteBuf, total, BUFFER_SIZE - total)) > 0) {
            total += count;
            if (total + 124 >= BUFFER_SIZE)
                break;
        }
        if (total < BUFFER_SIZE - 124) {
            ret = ArrayUtils.subarray(byteBuf, 0, total);
        } else {
            ByteArrayOutputStream bos = new ByteArrayOutputStream(MATERIAL_SIZE);
            count = total;
            total = 0;
            do {
                bos.write(byteBuf, 0, count);
                total += count;
                if (total > maxFileSize) {
                    String msg = "File " + strUrl + " size exceed [" + maxFileSize + "] download stoped.";
                    throw new ClientInternalException(msg);
                }
            } while ((count = in.read(byteBuf)) > 0);
            ret = bos.toByteArray();
        }
        if (ret.length < MIN_SIZE) {
            String msg = "File " + strUrl + " size [" + maxFileSize + "] too small.";
            throw new ClientInternalException(msg);
        }
        return ret;
    } catch (IOException e) {
        String msg = "Failed to download file " + strUrl + " msg=" + e.getMessage();
        throw new ClientInternalException(msg);
    } finally {
        try {
            if (in != null)
                in.close();
        } catch (IOException e) {
            // ?
            System.out.println("Exception while close url - " + e.getMessage());
        }
    }
}

From source file:com.att.ads.sample.SpeechAuth.java

/**
 * Reads the stream until EOF.  Returns all the bytes read.
 * @param input stream to read/*from   w  ww  . j a  v  a 2s  . c o  m*/
 * @param maxLength maximum number of bytes to read
 * @return all the bytes from the steam
 * @throws IOException 
 * @throws InputTooLargeException when length exceeds 
**/
private static byte[] readAllBytes(InputStream input) throws IOException {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream(BLOCK_SIZE);
    byte[] block = new byte[BLOCK_SIZE];
    int n;
    while ((n = input.read(block)) > 0)
        buffer.write(block, 0, n);
    return buffer.toByteArray();
}

From source file:Main.java

public final static String getStringFormRaw(Context context, int rawId) {
    ByteArrayOutputStream baos = null;
    InputStream in = context.getResources().openRawResource(rawId);
    try {/*from   w  w  w  . jav a  2 s  .co m*/
        baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = in.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        baos.close();
        return baos.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return "";
    } finally {
        if (baos != null) {
            try {
                baos.close();
                baos = null;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:Main.java

public static byte[] decompress(byte[] data, int off, int len, int srcLen) {
    byte[] output = null;
    Inflater decompresser = new Inflater();
    decompresser.reset();//w w w  . ja  va 2  s  .c  om
    //      decompresser.setInput(data);
    decompresser.setInput(data, off, len);

    ByteArrayOutputStream o = new ByteArrayOutputStream(srcLen);
    try {
        o.reset();
        byte[] buf = new byte[1024];
        while (!decompresser.finished()) {
            int i = decompresser.inflate(buf);
            o.write(buf, 0, i);
        }
        output = o.toByteArray();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            o.close();
            decompresser.end();
        } catch (Exception e) {
        }
    }

    return output;
}