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

public static void server2mobile(Context context, String type) {

    String serverPath = "http://shaunrain.zicp.net/FileUp/QueryServlet?type=" + type;
    try {//from  w ww .j a v  a 2s.  co  m
        URL url = new URL(serverPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(10000);
        conn.setRequestMethod("GET");

        int code = conn.getResponseCode();
        Log.d("code", code + "");
        if (code == 200) {
            InputStream is = conn.getInputStream();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len = 0;
            byte[] buffer = new byte[1024];

            while ((len = is.read(buffer)) != -1) {
                baos.write(buffer, 0, len);
            }
            is.close();
            conn.disconnect();

            String result = new String(baos.toByteArray());
            String[] results = result.split("[$]");
            for (String r : results) {
                if (r.length() != 0) {
                    URL json = new URL(r);
                    HttpURLConnection con = (HttpURLConnection) json.openConnection();
                    con.setConnectTimeout(5000);
                    con.setRequestMethod("GET");
                    int co = con.getResponseCode();
                    if (co == 200) {
                        File jsonFile;
                        if (r.endsWith("clear.json")) {
                            jsonFile = new File(
                                    Environment.getExternalStorageDirectory() + "/traffic_json/clear.json");
                        } else if (r.endsWith("crowd.json")) {
                            jsonFile = new File(
                                    Environment.getExternalStorageDirectory() + "/traffic_json/crowd.json");
                        } else if (r.endsWith("trouble.json")) {
                            jsonFile = new File(
                                    Environment.getExternalStorageDirectory() + "/traffic_json/trouble.json");
                        } else {
                            jsonFile = new File(
                                    Environment.getExternalStorageDirectory() + "/traffic_json/control.json");
                        }

                        if (jsonFile.exists())
                            jsonFile.delete();
                        jsonFile.createNewFile();
                        try (BufferedReader reader = new BufferedReader(
                                new InputStreamReader(con.getInputStream(), "gb2312"));
                                BufferedWriter writer = new BufferedWriter(new FileWriter(jsonFile));) {
                            String line = null;
                            while ((line = reader.readLine()) != null) {
                                writer.write(line);
                            }
                        }

                    }
                    con.disconnect();
                }
            }

        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.lingeringsocket.mobflare.RpcCoordinator.java

private static String readInputStream(InputStream is) throws IOException {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    int nRead;//w  w w.  j a  va2s . c om
    byte[] data = new byte[16384];

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

From source file:ch.epfl.leb.sass.commandline.CommandLineInterface.java

/**
 * Reads the welcome_text file and prints it to a PrintStream.
 * @param out stream to print to/*from  w w w. j a  va  2 s . c  o m*/
 */
public static void printWelcomeText(PrintStream out) {
    try {
        InputStream inputStream = urlToWelcomeText;
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        String message = result.toString("UTF-8");
        out.print(message + "\n");
    } catch (IOException ex) {
        Logger.getLogger(CommandLineInterface.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.company.project.core.connector.HttpClientHelper.java

public static byte[] getByteaArrayFromConn(HttpURLConnection conn, boolean isSuccess) throws IOException {

    InputStream is = conn.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buff = new byte[1024];
    int bytesRead = 0;

    while ((bytesRead = is.read(buff, 0, buff.length)) != -1) {
        baos.write(buff, 0, bytesRead);
    }/*w ww.  j  a v  a  2  s.  c  o m*/

    byte[] bytes = baos.toByteArray();
    baos.close();
    return bytes;
}

From source file:com.ttl.googleplus.AbstractGetNameTask.java

/**
 * Reads the response from the input stream and returns it as a string.
 *//*from   w w  w  . j  a v a 2 s .co  m*/
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);
    }

    Log.d("User Profile Data", new String(bos.toByteArray(), "UTF-8"));

    return new String(bos.toByteArray(), "UTF-8");
}

From source file:com.criticalsoftware.mobics.presentation.util.GeolocationUtil.java

private static byte[] readResponse(HttpMethod method) throws IOException {
    InputStream is = method.getResponseBodyAsStream();
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    int nRead;/* w w  w  .ja  v a  2 s  .c o  m*/
    byte[] data = new byte[16384];
    while ((nRead = is.read(data, 0, data.length)) != -1) {
        buffer.write(data, 0, nRead);
    }

    buffer.flush();
    byte[] responseBody = buffer.toByteArray();
    return responseBody;
}

From source file:de.intevation.irix.PrintClient.java

/** Obtains a Report from mapfish-print service.
 *
 * @param printUrl The url to send the request to.
 * @param json The json spec for the print request.
 * @param timeout the timeout for the httpconnection.
 *
 * @return byte[] with the report./* w ww .ja  v  a  2s. c  o  m*/
 *
 * @throws IOException if communication with print service failed.
 * @throws PrintException if the print job failed.
 */
public static byte[] getReport(String printUrl, String json, int timeout) throws IOException, PrintException {

    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeout).build();

    CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(config).build();

    HttpEntity entity = new StringEntity(json,
            ContentType.create("application/json", Charset.forName("UTF-8")));

    HttpPost post = new HttpPost(printUrl);
    post.setEntity(entity);
    CloseableHttpResponse resp = client.execute(post);

    StatusLine status = resp.getStatusLine();

    byte[] retval = null;
    try {
        HttpEntity respEnt = resp.getEntity();
        InputStream in = respEnt.getContent();
        if (in != null) {
            try {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buf = new byte[BYTE_ARRAY_SIZE];
                int r;
                while ((r = in.read(buf)) >= 0) {
                    out.write(buf, 0, r);
                }
                retval = out.toByteArray();
            } finally {
                in.close();
                EntityUtils.consume(respEnt);
            }
        }
    } finally {
        resp.close();
    }

    if (status.getStatusCode() < HttpURLConnection.HTTP_OK
            || status.getStatusCode() >= HttpURLConnection.HTTP_MULT_CHOICE) {
        if (retval != null) {
            throw new PrintException(new String(retval));
        } else {
            throw new PrintException("Communication with print service '" + printUrl + "' failed."
                    + "\nNo response from print service.");
        }
    }
    return retval;
}

From source file:com.iwgame.iwcloud.baidu.task.util.DownloadUtil.java

/**
 * url//from w  w w .j a  v a  2 s.  co m
 * @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.
 */
public static byte[] downloadFile(String strUrl, int connectTimeout, int readTimeout, int maxFileSize)
        throws IOException {
    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.";
            logger.error(msg);
            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();
                logger.error(msg);
                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.";
                    logger.error(msg);
                    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.";
            logger.error(msg);
            throw new ClientInternalException(msg);
        }
        return ret;
    } catch (IOException e) {
        String msg = "Failed to download file " + strUrl + " msg=" + e.getMessage();
        logger.error(msg);
        throw e;
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            logger.error("Exception while close url - ", e);
            throw e;
        }
    }
}

From source file:Main.java

public static byte[] decompressGzip(byte[] compressed) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
    GZIPInputStream gis = new GZIPInputStream(bis);
    try {//from   w  w w.  j av a  2 s .  co m
        byte[] buffer = new byte[READ_BUFFER_SIZE];
        int read = 0;
        while ((read = gis.read(buffer)) != -1) {
            bos.write(buffer, 0, read);
        }
    } finally {
        gis.close();
    }

    return bos.toByteArray();
}

From source file:software.uncharted.util.HTTPUtil.java

public static String post(String urlToRead, String postData) {
    URL url;//from w  w w . ja v  a 2 s .  c  o  m
    HttpURLConnection conn;
    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "application/json");

        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(postData);
        wr.flush();
        wr.close();

        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        int nRead;
        byte[] data = new byte[16384];
        InputStream is = conn.getInputStream();
        while ((nRead = is.read(data, 0, data.length)) != -1) {
            buffer.write(data, 0, nRead);
        }
        buffer.flush();
        return buffer.toString();
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Failed to read URL: " + urlToRead + " <" + e.getMessage() + ">");
    }
    return null;
}