Example usage for java.io OutputStream write

List of usage examples for java.io OutputStream write

Introduction

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

Prototype

public void write(byte b[]) throws IOException 

Source Link

Document

Writes b.length bytes from the specified byte array to this output stream.

Usage

From source file:Main.java

public static void writeCString(OutputStream out, String s, String characterSet, int fixedLen)
        throws IOException {
    byte[] bytes = s.getBytes(characterSet);
    out.write(bytes.length);
    fixedLen -= 1;/*  w ww  . j  a v a 2 s .  com*/

    if (fixedLen <= 0)
        return;

    if (fixedLen <= bytes.length) {
        out.write(bytes, 0, fixedLen);
    } else {
        out.write(bytes);
        byte[] fillBytes = new byte[fixedLen - bytes.length];
        Arrays.fill(fillBytes, (byte) 0);
        out.write(fillBytes);
    }

    out.flush();
}

From source file:com.ebay.nest.io.sede.lazy.LazyTimestamp.java

/**
 * Writes a Timestamp in JDBC timestamp format to the output stream
 * @param out//from w w w.j  av  a  2  s  . c  om
 *          The output stream
 * @param i
 *          The Timestamp to write
 * @throws IOException
 */
public static void writeUTF8(OutputStream out, TimestampWritable i) throws IOException {
    if (i == null) {
        // Serialize as time 0
        out.write(TimestampWritable.nullBytes);
    } else {
        out.write(i.toString().getBytes("US-ASCII"));
    }
}

From source file:com.google.android.gcm.demo.app.ServerUtilities.java

/**
 * Issue a POST request to the server.// w  w  w. j a  v a2s .co m
 *
 * @param endpoint POST address.
 * @param params request parameters.
 *
 * @throws IOException propagated from POST.
 */
private static void post(String endpoint, Map<String, String> params) throws IOException {
    URL url;
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    JSONObject jsonObj = new JSONObject(params);
    String body = jsonObj.toString();
    Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();
        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.nuvolect.deepdive.util.FileUtil.java

public static void writeFile(File file, String fileContents) {

    try {//from  w ww. jav a 2s .c o m
        OutputStream out = null;

        FileUtils.forceMkdirParent(file);

        out = new BufferedOutputStream(new FileOutputStream(file));

        out.write(fileContents.getBytes());

        if (out != null)
            out.close();
    } catch (IOException e) {
        LogUtil.log(FileUtil.class, "File write failed: " + e.toString());
    }
}

From source file:Main.java

public static void writeWString(OutputStream out, String s) throws IOException {
    byte[] bytes = s.getBytes();
    writeShort(out, bytes.length);/*from   w  w  w.ja va2  s  .c  o  m*/
    out.write(bytes);
    out.flush();
}

From source file:com.binil.pushnotification.ServerUtil.java

/**
 * Issue a POST request to the server./*from   www  .  j  a v a 2s  . c o m*/
 *
 * @param endpoint POST address.
 * @param params   request parameters.
 * @throws java.io.IOException propagated from POST.
 */
private static void post(String endpoint, Map<String, Object> params) throws IOException, JSONException {

    URL url = new URL(endpoint);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestMethod("POST");
    urlConnection.setRequestProperty("Cache-Control", "no-cache");
    urlConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
    urlConnection.setRequestProperty("Accept-Encoding", "gzip,deflate");
    urlConnection.setRequestProperty("Accept", "*/*");

    urlConnection.setDoOutput(true);

    JSONObject json = new JSONObject(params);
    String body = json.toString();
    urlConnection.setFixedLengthStreamingMode(body.length());

    try {
        OutputStream os = urlConnection.getOutputStream();
        os.write(body.getBytes("UTF-8"));
        os.close();

    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        int status = urlConnection.getResponseCode();
        String connectionMsg = urlConnection.getResponseMessage();
        urlConnection.disconnect();

        if (status != HttpURLConnection.HTTP_OK) {
            Log.wtf(TAG, connectionMsg);
            throw new IOException("Post failed with error code " + status);
        }
    }

}

From source file:Main.java

public static final void writeFix(OutputStream out, String s, String charsetName) throws IOException {
    if (s == null || s.length() == 0)
        return;/*from  w ww  .j  a  va 2  s .  co  m*/
    byte[] b = charsetName != null ? s.getBytes(charsetName) : s.getBytes();
    out.write(b);
}

From source file:com.adanac.module.blog.api.HttpApiHelper.java

public static void baiduPush(int remain) {
    String pushUrl = DaoFactory.getDao(HtmlPageDao.class).findPushUrl();
    if (pushUrl == null) {
        if (logger.isInfoEnabled()) {
            logger.info("all html page has been pushed!");
        }/*from  w w  w  . j a  v  a  2s  .  co  m*/
        return;
    }
    if (remain <= 0) {
        if (logger.isInfoEnabled()) {
            logger.info("there has no remain[" + remain + "]!");
        }
        return;
    }
    if (logger.isInfoEnabled()) {
        logger.info("find push url : " + pushUrl);
    }
    String url = "http://data.zz.baidu.com/urls?site=" + site + "&token=" + token;
    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/plain");
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(pushUrl.getBytes("UTF-8"));
        outputStream.write("\r\n".getBytes("UTF-8"));
        outputStream.flush();
        int status = connection.getResponseCode();
        if (logger.isInfoEnabled()) {
            logger.info("baidu-push response code : " + status);
        }
        if (status == HttpServletResponse.SC_OK) {
            String response = IOUtil.read(connection.getInputStream());
            if (logger.isInfoEnabled()) {
                logger.info("baidu-push response : " + response);
            }
            JSONObject result = JSONObject.fromObject(response);
            if (result.getInt("success") >= 1) {
                DaoFactory.getDao(HtmlPageDao.class).updateIsPush(pushUrl);
            } else {
                logger.warn("push url failed : " + pushUrl);
            }
            baiduPush(result.getInt("remain"));
        } else {
            logger.error("baidu-push error : " + IOUtil.read(connection.getErrorStream()));
        }
    } catch (Exception e) {
        logger.error("baidu push failed ...", e);
    }
}

From source file:com.usefullc.platform.common.utils.IOUtils.java

/**
 * //from   w ww  . j  av a 2s  . c  o  m
 * 
 * @param path
 * @param fileName
 * @param response
 * @return
 */
public static void download(String path, String fileName, HttpServletResponse response) {
    try {

        if (StringUtils.isEmpty(path)) {
            throw new IllegalArgumentException("?");
        } else {
            File file = new File(path);
            if (!file.exists()) {
                throw new IllegalArgumentException("??");
            }
        }
        if (StringUtils.isEmpty(fileName)) {
            throw new IllegalArgumentException("???");
        }
        if (response == null) {
            throw new IllegalArgumentException("response ?");
        }

        // path
        File file = new File(path);

        // ??
        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        // response
        response.reset();

        // ??linux ?  linux utf-8,windows  GBK)
        String defaultEncoding = System.getProperty("file.encoding");
        if (defaultEncoding != null && defaultEncoding.equals("UTF-8")) {

            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes("GBK"), "iso-8859-1"));
        } else {
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + new String(fileName.getBytes(), "iso-8859-1"));
        }

        // responseHeader
        response.addHeader("Content-Length", "" + file.length());
        response.setContentType("application/octet-stream");
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        toClient.write(buffer);
        toClient.flush();
        toClient.close();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:it.unicaradio.android.gcm.GcmServerRpcCall.java

/**
 * @param bytes//from  w w w. ja v a2s.  com
 * @param conn
 * @throws IOException
 */
private static void postRequest(HttpURLConnection conn, byte[] bytes) throws IOException {
    OutputStream out = conn.getOutputStream();
    out.write(bytes);
    out.close();
}