Example usage for java.io OutputStreamWriter write

List of usage examples for java.io OutputStreamWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:com.jamesgiang.aussnowcam.Utils.java

public static void WriteSettings(Context context, String data, String file) throws IOException {
    FileOutputStream fOut = null;
    OutputStreamWriter osw = null;
    fOut = context.openFileOutput(file, Context.MODE_PRIVATE);
    osw = new OutputStreamWriter(fOut);
    osw.write(data);
    osw.close();//from  w  ww  .  j  a va 2  s  .c o m
    fOut.close();
}

From source file:Main.java

public static File writeToSDFromInput(String path, String fileName, String data) {

    File file = null;//from   www .  ja  va 2 s .  co  m
    OutputStreamWriter outputWriter = null;
    OutputStream outputStream = null;
    try {
        creatSDDir(path);
        file = createFileInSDCard(fileName, path);
        outputStream = new FileOutputStream(file, false);
        outputWriter = new OutputStreamWriter(outputStream);
        outputWriter.write(data);
        outputWriter.flush();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            outputWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return file;
}

From source file:Main.java

public static int doShellCommand(String[] cmds, StringBuilder log, boolean runAsRoot, boolean waitFor)
        throws Exception {

    Process proc = null;/*  w  ww.j  a v a2 s .c  o  m*/
    int exitCode = -1;

    if (runAsRoot)
        proc = Runtime.getRuntime().exec("su");
    else
        proc = Runtime.getRuntime().exec("sh");

    OutputStreamWriter out = new OutputStreamWriter(proc.getOutputStream());

    for (int i = 0; i < cmds.length; i++) {
        Log.d("the-onion-phone",
                "executing shell cmd: " + cmds[i] + "; runAsRoot=" + runAsRoot + ";waitFor=" + waitFor);

        out.write(cmds[i]);
        out.write("\n");
    }

    out.flush();
    out.write("exit\n");
    out.flush();

    if (waitFor) {

        final char buf[] = new char[10];

        // Consume the "stdout"
        InputStreamReader reader = new InputStreamReader(proc.getInputStream());
        int read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        // Consume the "stderr"
        reader = new InputStreamReader(proc.getErrorStream());
        read = 0;
        while ((read = reader.read(buf)) != -1) {
            if (log != null)
                log.append(buf, 0, read);
        }

        exitCode = proc.waitFor();

    }

    return exitCode;

}

From source file:Main.java

public static String[] execSQL(String dbName, String query) {
    Process process = null;//w  w  w .jav a2s. co m
    Runtime runtime = Runtime.getRuntime();
    OutputStreamWriter outputStreamWriter;

    try {
        String command = dbName + " " + "'" + query + "'" + ";";
        process = runtime.exec("su");

        outputStreamWriter = new OutputStreamWriter(process.getOutputStream());

        outputStreamWriter.write("sqlite3 " + command);

        outputStreamWriter.flush();
        outputStreamWriter.close();
        outputStreamWriter.close();

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

    final InputStreamReader errorStreamReader = new InputStreamReader(process.getErrorStream());

    (new Thread() {
        @Override
        public void run() {
            try {

                BufferedReader bufferedReader = new BufferedReader(errorStreamReader);
                String s;
                while ((s = bufferedReader.readLine()) != null) {
                    Log.d("com.suraj.waext", "WhatsAppDBHelper:" + s);
                }

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

    }).start();

    try {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String s;
        StringBuilder op = new StringBuilder();

        while ((s = bufferedReader.readLine()) != null) {
            op.append(s).append("\n");
        }

        return op.toString().split("\n");
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return null;

}

From source file:com.amalto.workbench.utils.FileProvider.java

public static IFile createdTempFile(String templateString, String fileNameWithExtension, String charSet) {
    IFile file = null;//from   w  w  w.  j  a v a 2s.  c  o  m
    if (templateString != null) {
        try {
            Project project = ProjectManager.getInstance().getCurrentProject();
            IProject prj = ResourceUtils.getProject(project);
            file = prj.getFile(new Path("temp/" + fileNameWithExtension)); //$NON-NLS-1$

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            OutputStreamWriter outputStreamWriter = null;
            if ((charSet == null) || (charSet.trim().isEmpty())) {
                outputStreamWriter = new OutputStreamWriter(outputStream);
            } else {
                outputStreamWriter = new OutputStreamWriter(outputStream, charSet);
            }

            outputStreamWriter.write(templateString);
            outputStreamWriter.flush();
            outputStreamWriter.close();

            ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
            if (file.exists()) {
                file.setContents(inputStream, true, false, null);
            } else {
                file.create(inputStream, true, null);
            }

            inputStream.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    return file;
}

From source file:edu.jhu.cvrg.timeseriesstore.opentsdb.TimeSeriesUtility.java

protected static int insertDataPoints(String urlString, List<IncomingDataPoint> points) throws IOException {
    int code = 0;
    Gson gson = new Gson();

    HttpURLConnection httpConnection = TimeSeriesUtility.openHTTPConnectionPOST(urlString);
    OutputStreamWriter wr = new OutputStreamWriter(httpConnection.getOutputStream());

    String json = gson.toJson(points);

    wr.write(json);
    wr.flush();/*from   w  ww. ja v a2 s.  c om*/
    wr.close();

    code = httpConnection.getResponseCode();

    httpConnection.disconnect();

    return code;
}

From source file:com.memetix.mst.MicrosoftTranslatorAPI.java

/**
 * Gets the OAuth access token.//ww w  .ja va  2 s .c  om
 * @param clientId The Client key.
 * @param clientSecret The Client Secret
 */
public static String getToken(final String clientId, final String clientSecret) throws Exception {
    final String params = "grant_type=client_credentials&scope=http://api.microsofttranslator.com"
            + "&client_id=" + URLEncoder.encode(clientId, ENCODING) + "&client_secret="
            + URLEncoder.encode(clientSecret, ENCODING);

    final URL url = new URL(DatamarketAccessUri);
    final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    if (referrer != null)
        uc.setRequestProperty("referer", referrer);
    uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=" + ENCODING);
    uc.setRequestProperty("Accept-Charset", ENCODING);
    uc.setRequestMethod("POST");
    uc.setDoOutput(true);

    OutputStreamWriter wr = new OutputStreamWriter(uc.getOutputStream());
    wr.write(params);
    wr.flush();

    try {
        final int responseCode = uc.getResponseCode();
        final String result = inputStreamToString(uc.getInputStream());
        if (responseCode != 200) {
            throw new Exception("Error from Microsoft Translator API: " + result);
        }
        return result;
    } finally {
        if (uc != null) {
            uc.disconnect();
        }
    }
}

From source file:net.mindengine.oculus.frontend.web.controllers.display.FileDisplayController.java

public static void showTextFile(HttpServletResponse response, String path, String fileName, String contentType)
        throws IOException {

    OutputStream os = response.getOutputStream();
    OutputStreamWriter w = new OutputStreamWriter(os);
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
    response.setContentType(contentType);
    response.setCharacterEncoding("UTF-8");
    String content = readFileAsString(path);
    w.write(content);
    w.flush();/*from w w w .ja v a 2  s.  c om*/
    os.flush();
    os.close();
}

From source file:com.telefonica.iot.perseo.Utils.java

/**
 * Makes an HTTP POST to an URL sending an body. The URL and body are
 * represented as String./* w w w  . j av  a2s.  co  m*/
 *
 * @param urlStr String representation of the URL
 * @param content Styring representation of the body to post
 *
 * @return if the request has been accompished
 */

public static boolean DoHTTPPost(String urlStr, String content) {
    try {
        URL url = new URL(urlStr);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        urlConn.setRequestProperty(Constants.CORRELATOR_HEADER, MDC.get(Constants.CORRELATOR_ID));
        urlConn.setRequestProperty(Constants.SERVICE_HEADER, MDC.get(Constants.SERVICE_FIELD));
        urlConn.setRequestProperty(Constants.SUBSERVICE_HEADER, MDC.get(Constants.SUBSERVICE_FIELD));
        urlConn.setRequestProperty(Constants.REALIP_HEADER, MDC.get(Constants.REALIP_FIELD));

        OutputStreamWriter printout = new OutputStreamWriter(urlConn.getOutputStream(),
                Charset.forName("UTF-8"));
        printout.write(content);
        printout.flush();
        printout.close();

        int code = urlConn.getResponseCode();
        String message = urlConn.getResponseMessage();
        logger.debug("action http response " + code + " " + message);
        if (code / 100 == 2) {
            InputStream input = urlConn.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input));
            for (String line; (line = reader.readLine()) != null;) {
                logger.info("action response body: " + line);
            }
            input.close();
            return true;

        } else {
            logger.error("action response is not OK: " + code + " " + message);
            InputStream error = urlConn.getErrorStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(error));
            for (String line; (line = reader.readLine()) != null;) {
                logger.error("action error response body: " + line);
            }
            error.close();
            return false;
        }
    } catch (MalformedURLException me) {
        logger.error("exception MalformedURLException: " + me);
        return false;
    } catch (IOException ioe) {
        logger.error("exception IOException: " + ioe);
        return false;
    }
}

From source file:com.buglabs.dragonfly.util.WSHelper.java

/**
 * Post contents of input stream to URL.
 * /*from  w  w  w.j  a v a 2s  .  com*/
 * @param url
 * @param stream
 * @return
 * @throws IOException
 */
protected static String postBase64(URL url, InputStream stream) throws IOException {
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);

    byte[] buff = streamToByteArray(stream);

    String em = Base64.encodeBytes(buff);
    OutputStreamWriter osr = new OutputStreamWriter(conn.getOutputStream());
    osr.write(em);
    osr.flush();

    stream.close();
    conn.getOutputStream().flush();
    conn.getOutputStream().close();

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line, resp = new String("");
    while ((line = rd.readLine()) != null) {
        resp = resp + line + "\n";
    }
    rd.close();

    return resp;
}