Example usage for java.io OutputStreamWriter close

List of usage examples for java.io OutputStreamWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:com.pureinfo.srm.outlay.action.SearchCheckCodeAction.java

/**
 * /*  w w w .j a v  a2  s .  co m*/
 * @param strUrl
 * @param strPostRequest
 * @return
 */
public static String getPageContent(String strUrl, String strPostRequest) {
    //
    StringBuffer buffer = new StringBuffer();
    System.setProperty("sun.net.client.defaultConnectTimeout", "5000");
    System.setProperty("sun.net.client.defaultReadTimeout", "5000");
    try {
        URL newUrl = new URL(strUrl);
        HttpURLConnection hConnect = (HttpURLConnection) newUrl.openConnection();
        //POST
        if (strPostRequest.length() > 0) {
            hConnect.setDoOutput(true);
            OutputStreamWriter out = new OutputStreamWriter(hConnect.getOutputStream());
            out.write(strPostRequest);
            out.flush();
            out.close();
        }
        //
        BufferedReader rd = new BufferedReader(new InputStreamReader(hConnect.getInputStream()));
        int ch;
        for (int length = 0; (ch = rd.read()) > -1; length++)
            buffer.append((char) ch);
        rd.close();
        hConnect.disconnect();
        return buffer.toString().trim();
    } catch (Exception e) {
        // return ":";
        return null;
    } finally {
        buffer.setLength(0);
    }
}

From source file:es.tid.cep.esperanza.Utils.java

public static boolean DoHTTPPost(String urlStr, String content) {
    try {//from w ww .j  a  v  a  2s .co  m
        URL url = new URL(urlStr);
        HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        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.debug("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.getMessage());
        return false;
    } catch (IOException ioe) {
        logger.error("exception IOException: " + ioe.getMessage());
        return false;
    }
}

From source file:Main.java

/**
 * Writes the current app logcat to a file.
 *
 * @param filename The filename to save it as
 * @throws IOException/*from   w  ww.  j  a v a  2  s .  c o  m*/
 */
public static void writeLogcat(String filename) throws IOException {
    String[] args = { "logcat", "-v", "time", "-d" };

    Process process = Runtime.getRuntime().exec(args);
    InputStreamReader input = new InputStreamReader(process.getInputStream());
    OutputStreamWriter output = new OutputStreamWriter(new FileOutputStream(filename));
    BufferedReader br = new BufferedReader(input);
    BufferedWriter bw = new BufferedWriter(output);
    String line;

    while ((line = br.readLine()) != null) {
        bw.write(line);
        bw.newLine();
    }

    bw.close();
    output.close();
    br.close();
    input.close();
}

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);/*  ww  w  .  j  av a  2  s  .  com*/
    osw.close();
    fOut.close();
}

From source file:lu.list.itis.dkd.aig.util.FusekiHttpHelper.java

/**
 * Create a new dataset/*from  w w w . j  a  v  a 2  s  .  c  om*/
 * 
 * @param dataSetName
 * @throws IOException
 * @throws HttpException
 */
public static void createDataSet(@NonNull String dataSetName) throws IOException, HttpException {
    logger.info("create dataset: " + dataSetName);

    URL url = new URL(HOST + "/$/datasets");
    final HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
    httpConnection.setUseCaches(false);
    httpConnection.setRequestMethod("POST");
    httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    // set content
    httpConnection.setDoOutput(true);
    final OutputStreamWriter out = new OutputStreamWriter(httpConnection.getOutputStream());
    out.write("dbName=" + URLEncoder.encode(dataSetName, "UTF-8") + "&dbType=mem");
    out.close();

    // handle HTTP/HTTPS strange behaviour
    httpConnection.connect();
    httpConnection.disconnect();

    // handle response
    switch (httpConnection.getResponseCode()) {
    case HttpURLConnection.HTTP_OK:
        break;
    default:
        throw new HttpException(
                httpConnection.getResponseCode() + " message: " + httpConnection.getResponseMessage());
    }
}

From source file:Main.java

public static Uri getSMSLogs(ContentResolver cr, Uri internal, Context context, String timeStamp) {
    String[] smsLogArray = new String[2];
    Uri uri = Uri.parse("content://sms/inbox");
    Cursor cur = cr.query(uri, null, null, null, null);
    FileOutputStream fOut = null;

    try {//  w ww .j  a v a2  s  .c om
        fOut = context.openFileOutput("sms_logs_" + timeStamp + ".txt", Context.MODE_PRIVATE);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    OutputStreamWriter osw = new OutputStreamWriter(fOut);

    while (cur.moveToNext()) {
        smsLogArray[0] = cur.getString(cur.getColumnIndexOrThrow("address")).toString();
        smsLogArray[1] = cur.getString(cur.getColumnIndexOrThrow("body")).toString();

        writeToOutputStreamArray(smsLogArray, osw);
    }

    try {
        osw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return internal;
}

From source file:Main.java

public static Uri getSMSLogs(ContentResolver cr, Uri internal, Context context, String timeStamp) {
    String[] smsLogArray = new String[2];
    Uri uri = Uri.parse("content://sms/inbox");
    Cursor cur = cr.query(uri, null, null, null, null);
    //Cursor cur= cr.query(uri, smsLogArray, null ,null,null);
    FileOutputStream fOut = null;

    try {//from w w  w . j av a 2 s. c o  m
        fOut = context.openFileOutput("sms_logs_" + timeStamp + ".txt", Context.MODE_PRIVATE);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    OutputStreamWriter osw = new OutputStreamWriter(fOut);

    while (cur.moveToNext()) {
        smsLogArray[0] = cur.getString(cur.getColumnIndexOrThrow("address")).toString();
        smsLogArray[1] = cur.getString(cur.getColumnIndexOrThrow("body")).toString();

        writeToOutputStreamArray(smsLogArray, osw);
    }

    try {
        osw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return internal;
}

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);//from  w w  w  . ja va2s .c  om
    wr.flush();
    wr.close();

    code = httpConnection.getResponseCode();

    httpConnection.disconnect();

    return code;
}

From source file:org.apache.solr.client.solrj.SolrSchemalessExampleTest.java

@BeforeClass
public static void beforeClass() throws Exception {
    File tempSolrHome = createTempDir().toFile();
    // Schemaless renames schema.xml -> schema.xml.bak, and creates + modifies conf/managed-schema,
    // which violates the test security manager's rules, which disallow writes outside the build dir,
    // so we copy the example/example-schemaless/solr/ directory to a new temp dir where writes are allowed.
    FileUtils.copyFileToDirectory(new File(ExternalPaths.SERVER_HOME, "solr.xml"), tempSolrHome);
    File collection1Dir = new File(tempSolrHome, "collection1");
    FileUtils.forceMkdir(collection1Dir);
    FileUtils.copyDirectoryToDirectory(new File(ExternalPaths.SCHEMALESS_CONFIGSET), collection1Dir);
    Properties props = new Properties();
    props.setProperty("name", "collection1");
    OutputStreamWriter writer = null;
    try {//ww w .  java2 s .  com
        writer = new OutputStreamWriter(FileUtils.openOutputStream(new File(collection1Dir, "core.properties")),
                "UTF-8");
        props.store(writer, null);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (Exception ignore) {
            }
        }
    }
    createJetty(tempSolrHome.getAbsolutePath());
}

From source file:de.mas.telegramircbot.utils.images.ImgurUploader.java

public static String uploadImageAndGetLink(String clientID, byte[] image) throws IOException {
    URL url;/*from www.  j a v  a2s . c  o  m*/
    url = new URL(Settings.IMGUR_API_URL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    String dataImage = Base64.getEncoder().encodeToString(image);
    String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(dataImage, "UTF-8");

    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Client-ID " + clientID);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    conn.connect();
    StringBuilder stb = new StringBuilder();
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        stb.append(line).append("\n");
    }
    wr.close();
    rd.close();

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(ImgurResponse.class, new ImgurResponseDeserializer());
    Gson gson = gsonBuilder.create();

    // The JSON data
    try {
        ImgurResponse response = gson.fromJson(stb.toString(), ImgurResponse.class);
        return response.getLink();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return stb.toString();
}