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.qatickets.common.ZIPHelper.java

public static byte[] compress(byte[] data) {

    // Create the compressor with highest level of compression
    final Deflater compressor = new Deflater();
    compressor.setLevel(Deflater.BEST_COMPRESSION);

    // Give the compressor the data to compress
    compressor.setInput(data);/*from w  ww. java 2  s . c om*/
    compressor.finish();

    // Create an expandable byte array to hold the compressed data.
    // You cannot use an array that's the same size as the orginal because
    // there is no guarantee that the compressed data will be smaller than
    // the uncompressed data.
    final ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);

    // Compress the data
    byte[] buf = new byte[1024];
    while (!compressor.finished()) {
        final int count = compressor.deflate(buf);
        bos.write(buf, 0, count);
    }
    try {
        bos.close();
    } catch (IOException e) {
    }

    // Get the compressed data
    final byte[] compressedData = bos.toByteArray();

    compressor.end();

    return compressedData;
}

From source file:Main.java

public static byte[] gzipDecodeByteArray(byte[] data) {
    GZIPInputStream gzipInputStream = null;
    try {//from  ww w . ja va  2 s.  c  o m
        gzipInputStream = new GZIPInputStream(new ByteArrayInputStream(data));

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
        byte[] buffer = new byte[1024];
        while (gzipInputStream.available() > 0) {
            int count = gzipInputStream.read(buffer, 0, 1024);
            if (count > 0) {
                //System.out.println("Read " + count + " bytes");
                outputStream.write(buffer, 0, count);
            }
        }

        outputStream.close();
        gzipInputStream.close();
        return outputStream.toByteArray();
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.cpyf.twelve.spies.qr.code.result.supplement.ProductResultInfoRetriever.java

private static String consume(HttpEntity entity) {
    Log.d(TAG, "Consuming entity");
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InputStream in = null;/*from  w  w w .j  a v a2  s . c om*/
    try {
        in = entity.getContent();
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = in.read(buffer)) > 0) {
            out.write(buffer, 0, bytesRead);
        }
    } catch (IOException ioe) {
        Log.w(TAG, ioe);
        // continue
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException ioe) {
                // continue
            }
        }
    }
    try {
        return new String(out.toByteArray(), "UTF-8");
    } catch (UnsupportedEncodingException uee) {
        // can't happen
        throw new IllegalStateException(uee);
    }
}

From source file:Main.java

/**
 * Gets binary from uri.//from ww w  . ja v  a2 s . c  o  m
 *
 * @param context context
 * @param uri     uri
 * @return byte[] or null on error
 */
public static byte[] getContentData(final Context context, final String uri) {
    if (uri == null) {
        return null;
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InputStream in = null;
    byte[] buf = new byte[BUF_SIZE];
    int len;
    try {
        ContentResolver r = context.getContentResolver();
        in = r.openInputStream(Uri.parse(uri));
        while ((len = in.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
        return out.toByteArray();
    } catch (IOException e) {
        return null;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:outfox.dict.contest.util.FileUtils.java

/**
 * //from w w w. j  av a 2 s.c  o m
 * @param file
 * @return
 */
public static byte[] getBytesFromFile(File file) {
    byte[] byteArray = null;
    try {
        if (file == null) {
            return null;
        }
        FileInputStream in = new FileInputStream(file);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] b = new byte[4096];
        int n;
        while ((n = in.read(b)) != -1) {
            out.write(b, 0, n);
        }
        byteArray = out.toByteArray();
        in.close();
        out.close();
    } catch (IOException e) {
        LOG.error("FileUtils.getBytesFromFile error...", e);
    }
    return byteArray;
}

From source file:io.card.development.recording.Recording.java

private static Hashtable<String, byte[]> unzipFiles(InputStream recordingStream) throws IOException {
    ZipEntry zipEntry;/*from www.  java  2 s .c o  m*/
    ZipInputStream zis = new ZipInputStream(recordingStream);
    Hashtable<String, byte[]> fileHash = new Hashtable<String, byte[]>();
    byte[] buffer = new byte[512];

    while ((zipEntry = zis.getNextEntry()) != null) {
        if (!zipEntry.isDirectory()) {
            int read = 0;
            ByteArrayOutputStream fileStream = new ByteArrayOutputStream();

            do {
                read = zis.read(buffer, 0, buffer.length);
                if (read != -1) {
                    fileStream.write(buffer, 0, read);
                }
            } while (read != -1);

            byte[] fileData = fileStream.toByteArray();
            fileHash.put(zipEntry.getName(), fileData);
        }
    }

    return fileHash;
}

From source file:at.uni_salzburg.cs.ckgroup.cscpp.utils.HttpQueryUtils.java

public static String simpleQuery(String url) throws IOException {

    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);
    HttpResponse response;//from   ww w. j  av a 2s.  co m

    response = httpclient.execute(httpget);
    ByteArrayOutputStream bo = new ByteArrayOutputStream();

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        int l;
        byte[] tmp = new byte[2048];
        while ((l = instream.read(tmp)) != -1) {
            bo.write(tmp, 0, l);
        }
    }

    return bo.toString();
}

From source file:com.arellomobile.android.push.utils.NetworkUtils.java

public static NetworkResult makeRequest(Map<String, Object> data, String methodName) throws Exception {
    NetworkResult result = new NetworkResult(500, null);
    OutputStream connectionOutput = null;
    InputStream inputStream = null;
    try {/*from w ww .  j a va  2  s.c  o  m*/
        String urlString = NetworkUtils.BASE_URL + methodName;
        if (useSSL)
            urlString = NetworkUtils.BASE_URL_SECURE + methodName;

        URL url = new URL(urlString);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json; charset=utf-8");

        connection.setDoOutput(true);

        JSONObject innerRequestJson = new JSONObject();

        for (String key : data.keySet()) {
            innerRequestJson.put(key, data.get(key));
        }

        JSONObject requestJson = new JSONObject();
        requestJson.put("request", innerRequestJson);

        connection.setRequestProperty("Content-Length",
                String.valueOf(requestJson.toString().getBytes().length));

        connectionOutput = connection.getOutputStream();
        connectionOutput.write(requestJson.toString().getBytes());
        connectionOutput.flush();
        connectionOutput.close();

        inputStream = new BufferedInputStream(connection.getInputStream());

        ByteArrayOutputStream dataCache = new ByteArrayOutputStream();

        // Fully read data
        byte[] buff = new byte[1024];
        int len;
        while ((len = inputStream.read(buff)) >= 0) {
            dataCache.write(buff, 0, len);
        }

        // Close streams
        dataCache.close();

        String jsonString = new String(dataCache.toByteArray()).trim();
        Log.w(TAG, "PushWooshResult: " + jsonString);

        JSONObject resultJSON = new JSONObject(jsonString);

        result.setData(resultJSON);
        result.setCode(resultJSON.getInt("status_code"));
    } finally {
        if (null != inputStream) {
            inputStream.close();
        }
        if (null != connectionOutput) {
            connectionOutput.close();
        }
    }

    return result;
}

From source file:cf.client.UnexpectedResponseException.java

private static String readResponseBody(HttpResponse response) {
    final HttpEntity entity = response.getEntity();
    if (entity == null) {
        return null;
    }// w  ww  . j  av  a  2s.  co m
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] buffer = new byte[4096];
    try (InputStream in = entity.getContent()) {
        while (true) {
            int size = in.read(buffer, 0, buffer.length);
            if (size < 0) {
                break;
            }
            out.write(buffer, 0, size);
        }
    } catch (IOException e) {
        // If we get an error trying to read the body, just swallow it and return null.
        return null;
    }
    return new String(out.toByteArray());
}

From source file:Main.java

static byte[] readInputStream(InputStream inputStream) {
    byte[] bArr = null;
    if (inputStream != null) {
        try {//  w  w w  .  j a v  a  2 s . co  m
            ByteArrayOutputStream result = new ByteArrayOutputStream();
            byte[] buffer = new byte[16384];
            while (true) {
                int chunkSize = inputStream.read(buffer);
                if (chunkSize < 0) {
                    break;
                } else if (chunkSize > 0) {
                    result.write(buffer, 0, chunkSize);
                }
            }
            bArr = result.toByteArray();
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                }
            }
        } catch (IOException e2) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e3) {
                }
            }
        } catch (Throwable th) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e4) {
                }
            }
        }
    }
    return bArr;
}