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:com.log4ic.compressor.utils.FileUtils.java

/**
 * InputStream?????String// w ww . ja  v  a 2s. com
 *
 * @param in
 * @param encoding
 * @return
 * @throws Exception
 */
public static String InputStream2String(InputStream in, String encoding) throws Exception {
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    byte[] data = new byte[1024];
    int count = -1;
    while ((count = in.read(data, 0, 1024)) != -1)
        outStream.write(data, 0, count);

    data = null;
    return new String(outStream.toByteArray(), encoding);
}

From source file:Main.java

/**
 * decompress a gzip byte array, using a default buffer length of 1024
 * <p>/*ww w. j  ava 2 s .  co  m*/
 * @param compressedByteArray gzip-compressed byte array
 * @param bufferlength size of the buffer in bytes
 * @return decompressed byte array
 * @throws IOException thrown if there was a failure to construct the GzipInputStream
 */
public static byte[] decompressGzipByteArray(byte[] compressedByteArray, int bufferlength) throws IOException {
    ByteArrayOutputStream uncompressedStream = new ByteArrayOutputStream();

    GZIPInputStream compressedStream = new GZIPInputStream(new ByteArrayInputStream(compressedByteArray));

    byte[] buffer = new byte[bufferlength];

    int index = -1;

    while ((index = compressedStream.read(buffer)) != -1) {
        uncompressedStream.write(buffer, 0, index);
    }

    return uncompressedStream.toByteArray();
}

From source file:org.dataone.proto.trove.mn.http.client.DataHttpClientHandler.java

public static synchronized String executePost(HttpClient httpclient, HttpPost httpPost)
        throws ServiceFailure, NotFound, InvalidToken, NotAuthorized, IdentifierNotUnique, UnsupportedType,
        InsufficientResources, InvalidSystemMetadata, NotImplemented, InvalidCredentials, InvalidRequest,
        AuthenticationTimeout, UnsupportedMetadataType, HttpException {
    String response = null;/*from  ww w.  ja v  a 2 s .  c o m*/

    try {
        HttpResponse httpResponse = httpclient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
            HttpEntity resEntity = httpResponse.getEntity();
            if (resEntity != null) {
                logger.debug("Response content length: " + resEntity.getContentLength());
                logger.debug("Chunked?: " + resEntity.isChunked());
                BufferedInputStream in = new BufferedInputStream(resEntity.getContent());
                ByteArrayOutputStream resOutputStream = new ByteArrayOutputStream();
                byte[] buff = new byte[32 * 1024];
                int len;
                while ((len = in.read(buff)) > 0) {
                    resOutputStream.write(buff, 0, len);
                }
                response = new String(resOutputStream.toByteArray());
                logger.debug(response);
                resOutputStream.close();
                in.close();
            }
        } else {
            HttpExceptionHandler.deserializeAndThrowException(httpResponse);
        }
    } catch (IOException ex) {
        throw new ServiceFailure("1002", ex.getMessage());
    }
    return response;
}

From source file:Main.java

/**
 * Read a text file into a String, optionally limiting the length.
 * //from  www  . j a  v a 2  s.c  om
 * @param file
 *            to read (will not seek, so things like /proc files are OK)
 * @param max
 *            length (positive for head, negative of tail, 0 for no limit)
 * @param ellipsis
 *            to add of the file was truncated (can be null)
 * @return the contents of the file, possibly truncated
 * @throws IOException
 *             if something goes wrong reading the file
 */
public static String readTextFile(File file, int max, String ellipsis) throws IOException {
    InputStream input = new FileInputStream(file);
    try {
        long size = file.length();
        if (max > 0 || (size > 0 && max == 0)) { // "head" mode: read the
                                                 // first N bytes
            if (size > 0 && (max == 0 || size < max))
                max = (int) size;
            byte[] data = new byte[max + 1];
            int length = input.read(data);
            if (length <= 0)
                return "";
            if (length <= max)
                return new String(data, 0, length);
            if (ellipsis == null)
                return new String(data, 0, max);
            return new String(data, 0, max) + ellipsis;
        } else if (max < 0) { // "tail" mode: keep the last N
            int len;
            boolean rolled = false;
            byte[] last = null, data = null;
            do {
                if (last != null)
                    rolled = true;
                byte[] tmp = last;
                last = data;
                data = tmp;
                if (data == null)
                    data = new byte[-max];
                len = input.read(data);
            } while (len == data.length);

            if (last == null && len <= 0)
                return "";
            if (last == null)
                return new String(data, 0, len);
            if (len > 0) {
                rolled = true;
                System.arraycopy(last, len, last, 0, last.length - len);
                System.arraycopy(data, 0, last, last.length - len, len);
            }
            if (ellipsis == null || !rolled)
                return new String(last);
            return ellipsis + new String(last);
        } else { // "cat" mode: size unknown, read it all in streaming
                 // fashion
            ByteArrayOutputStream contents = new ByteArrayOutputStream();
            int len;
            byte[] data = new byte[1024];
            do {
                len = input.read(data);
                if (len > 0)
                    contents.write(data, 0, len);
            } while (len == data.length);
            return contents.toString();
        }
    } finally {
        input.close();
    }
}

From source file:SwingResourceManager.java

/**
 * Returns an image encoded by the specified input stream
 * @param is InputStream The input stream encoding the image data
 * @return Image The image encoded by the specified input stream
 *///from  www. j a  v a  2 s  . c o  m
private static Image getImage(InputStream is) {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte buf[] = new byte[1024 * 4];
        while (true) {
            int n = is.read(buf);
            if (n == -1)
                break;
            baos.write(buf, 0, n);
        }
        baos.close();
        return Toolkit.getDefaultToolkit().createImage(baos.toByteArray());
    } catch (Throwable e) {
        return null;
    }
}

From source file:com.thinkbiganalytics.feedmgr.util.ImportUtil.java

public static byte[] streamToByteArray(InputStream inputStream) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    int n;//from  w ww .j  av  a 2s .co m
    while ((n = inputStream.read(buf)) >= 0) {
        baos.write(buf, 0, n);
    }
    byte[] content = baos.toByteArray();
    return content;
}

From source file:com.asual.lesscss.ResourcePackage.java

private static byte[] inflate(byte[] output) throws DataFormatException, IOException {
    Inflater inflater = new Inflater();
    inflater.setInput(output);/*from   ww  w. ja va  2s.c o m*/
    ByteArrayOutputStream baos = new ByteArrayOutputStream(output.length);
    byte[] buf = new byte[1024];
    while (!inflater.finished()) {
        int count = inflater.inflate(buf);
        baos.write(buf, 0, count);
    }
    baos.close();
    return baos.toByteArray();
}

From source file:Main.java

public static byte[] inputStream2ByteArray(InputStream is, int bufferSize) throws IOException {
    if (null == is) {
        return null;
    }//from w ww .ja v a 2  s.  c o  m
    if (bufferSize < 1) {
        bufferSize = 1;
    }
    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();

    // this is storage overwritten on each iteration with bytes
    byte[] buffer = new byte[bufferSize];

    // we need to know how may bytes were read to write them to the
    // byteBuffer
    int len = 0;
    while ((len = is.read(buffer)) != -1) {
        byteBuffer.write(buffer, 0, len);
    }

    byteBuffer.close();
    is.close();

    // and then we can return your byte array.
    return byteBuffer.toByteArray();
}

From source file:Main.java

/**
 * Decompresses the given byte[] and returns the Object.
 * // www  .  j a v a 2  s . c o m
 * @param <T> Type of expected Object
 * @param bytes compressed byte[]
 * @param bufferSize size of buffer to be used (in bytes)
 * 
 * @return decompressed Object
 * 
 * @throws IOException if failed to decompress
 * @throws ClassCastException if cannot cast to specified type
 */
@SuppressWarnings("unchecked")
/* Ignore Unchecked Cast Warning */
public static <T> T decompress(byte[] bytes, int bufferSize) throws IOException, ClassCastException {

    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(bufferSize);
        Inflater inflater = new Inflater();
        inflater.setInput(bytes);

        // Decompress
        byte[] buf = new byte[bufferSize];
        while (!inflater.finished()) {
            int count = inflater.inflate(buf);
            bos.write(buf, 0, count);
        }
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));

        return (T) ois.readObject();
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:com.asual.lesscss.ResourcePackage.java

private static byte[] deflate(byte[] input) throws IOException {
    Deflater deflater = new Deflater();
    deflater.setLevel(Deflater.BEST_COMPRESSION);
    deflater.setInput(input);//from w w w.j  a  v a2  s.c  o m
    deflater.finish();
    ByteArrayOutputStream baos = new ByteArrayOutputStream(input.length);
    byte[] buf = new byte[1024];
    while (!deflater.finished()) {
        int count = deflater.deflate(buf);
        baos.write(buf, 0, count);
    }
    baos.close();
    return baos.toByteArray();
}