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:layout.FragmentBoardItemList.java

@Override
public boolean onContextItemSelected(MenuItem item) {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
    if (info.targetView.getParent() == listViewBoardItems) {
        BoardItem bi = boardItems.get(info.position);
        switch (item.getItemId()) {
        case R.id.menu_copy:
            System.out.println("Post copiado");
            ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData cd = ClipData.newPlainText("Reply", boardItems.get(info.position).getMessage());
            cm.setPrimaryClip(cd);/* ww  w.j  a va  2s  .c o  m*/
            break;
        case R.id.menu_reply:
            Intent in = new Intent(getActivity().getApplicationContext(), ResponseActivity.class);
            Bundle b = new Bundle();
            b.putParcelable("theReply", boardItems.get(info.position));
            b.putBoolean("quoting", true);
            in.putExtras(b);
            getActivity().startActivity(in);
            break;
        case R.id.menu_savereply:
            try {
                File txt = new File(Environment.getExternalStorageDirectory().getPath() + "/Bai/"
                        + bi.getParentBoard().getBoardDir() + "_" + bi.getId() + ".txt");
                FileOutputStream stream = new FileOutputStream(txt);
                OutputStreamWriter outputStreamWriter = new OutputStreamWriter(stream);
                outputStreamWriter.write(bi.getMessage());
                outputStreamWriter.close();
                stream.close();
                Toast.makeText(getContext(),
                        bi.getParentBoard().getBoardDir() + "_" + bi.getId() + ".txt guardado.",
                        Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
            break;
        case R.id.menu_delpost:
            deletePost(false, bi);
            break;
        case R.id.menu_delimage:
            deletePost(true, bi);
            break;
        }
    }
    return super.onContextItemSelected(item);
}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.output.OutputWriter.java

/** Output the data for the given session to the given path, if the session exists */
public boolean outputSession(int sessionId, String path) {
    try {// w ww.jav a  2  s . c o m
        if (!sessionExists(sessionId)) {
            log.warn("Session " + sessionId + " does not exist -- cannot write output file");
            return false;
        }

        File file = new File(path);
        file.createNewFile();

        FileOutputStream outStream = new FileOutputStream(file);
        OutputStreamWriter writer = new OutputStreamWriter(outStream);

        OutputTable txnTable = new TransactionHistoryTable(dbw, sessionId);
        OutputFormatter formatter = new CSVFormatter();

        String output = formatter.formatTable(txnTable);

        writer.write(output);

        OutputTable orderTable = new OrderHistoryTable(dbw, sessionId);
        formatter = new CSVFormatter();

        output = formatter.formatTable(orderTable);

        writer.write(output);

        OutputTable subjectTable = new SubjectTable(dbw, sessionId);
        formatter = new CSVFormatter();
        output = formatter.formatTable(subjectTable);
        writer.write(output);

        OutputTable payoffTable = new PayoffTable(dbw, sessionId);
        output = formatter.formatTable(payoffTable);
        writer.write(output);

        writer.close();
        outStream.close();

        return true;
    } catch (Exception e) {
        log.error("Error attempting to write output file for session " + sessionId, e);
    }
    return false;
}

From source file:de.uni_koeln.spinfo.maalr.services.editor.server.EditorServiceImpl.java

public void export(Set<String> fields, MaalrQuery query, File dest) throws IOException, InvalidQueryException,
        NoIndexAvailableException, BrokenIndexException, InvalidTokenOffsetsException {
    query.setPageNr(0);//  w ww . j  a  v a  2s .  co m
    query.setPageSize(50);
    ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(dest));
    zout.putNextEntry(new ZipEntry("exported.tsv"));
    OutputStream out = new BufferedOutputStream(zout);
    OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
    for (String field : fields) {
        writer.write(field);
        writer.write("\t");
    }
    writer.write("\n");
    while (true) {
        QueryResult result = index.query(query, false);
        if (result == null || result.getEntries() == null || result.getEntries().size() == 0)
            break;
        List<LemmaVersion> entries = result.getEntries();
        for (LemmaVersion version : entries) {
            write(writer, version, fields);
            writer.write("\n");
        }
        query.setPageNr(query.getPageNr() + 1);
    }
    writer.flush();
    zout.closeEntry();
    writer.close();

}

From source file:com.google.ytd.SubmitActivity.java

private String uploadMetaData(String filePath, boolean retry) throws IOException {
    String uploadUrl = INITIAL_UPLOAD_URL;

    HttpURLConnection urlConnection = getGDataUrlConnection(uploadUrl);
    urlConnection.setRequestMethod("POST");
    urlConnection.setDoOutput(true);//w w  w .j av  a2 s  . c  o m
    urlConnection.setRequestProperty("Content-Type", "application/atom+xml");
    urlConnection.setRequestProperty("Slug", filePath);
    String atomData;

    String title = getTitleText();
    String description = getDescriptionText();
    String category = DEFAULT_VIDEO_CATEGORY;
    this.tags = DEFAULT_VIDEO_TAGS;

    if (!Util.isNullOrEmpty(this.getTagsText())) {
        this.tags = this.getTagsText();
    }

    if (this.videoLocation == null) {
        String template = Util.readFile(this, R.raw.gdata).toString();
        atomData = String.format(template, title, description, category, this.tags);
    } else {
        String template = Util.readFile(this, R.raw.gdata_geo).toString();
        atomData = String.format(template, title, description, category, this.tags, videoLocation.getLatitude(),
                videoLocation.getLongitude());
    }

    OutputStreamWriter outStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
    outStreamWriter.write(atomData);
    outStreamWriter.close();

    int responseCode = urlConnection.getResponseCode();
    if (responseCode < 200 || responseCode >= 300) {
        // The response code is 40X
        if ((responseCode + "").startsWith("4") && retry) {
            Log.d(LOG_TAG, "retrying to fetch auth token for " + youTubeName);
            this.clientLoginToken = authorizer.getFreshAuthToken(youTubeName, clientLoginToken);
            // Try again with fresh token
            return uploadMetaData(filePath, false);
        } else {
            throw new IOException(String.format("response code='%s' (code %d)" + " for %s",
                    urlConnection.getResponseMessage(), responseCode, urlConnection.getURL()));
        }
    }

    return urlConnection.getHeaderField("Location");
}

From source file:biblivre3.cataloging.holding.HoldingBO.java

private File createIsoFile(Database database) {
    try {/*  w ww  . j a  va 2  s.c  o  m*/
        File file = File.createTempFile("bib3_", null);
        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8");
        HoldingDAO holdingDao = new HoldingDAO();
        int limit = 100;
        int recordCount = holdingDao.countAll(database);

        for (int offset = 0; offset < recordCount; offset += limit) {
            List<HoldingDTO> records = holdingDao.list(database, offset, limit);
            for (HoldingDTO dto : records) {
                writer.write(dto.getIso2709());
                writer.write(ApplicationConstants.LINE_BREAK);
            }
        }
        writer.flush();
        writer.close();
        return file;
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return null;
}

From source file:com.omertron.themoviedbapi.tools.WebBrowser.java

public static String request(URL url, String jsonBody, boolean isDeleteRequest) throws MovieDbException {

    StringWriter content = null;// w w w  .  j  ava2s  .co  m

    try {
        content = new StringWriter();

        BufferedReader in = null;
        HttpURLConnection cnx = null;
        OutputStreamWriter wr = null;
        try {
            cnx = (HttpURLConnection) openProxiedConnection(url);

            // If we get a null connection, then throw an exception
            if (cnx == null) {
                throw new MovieDbException(MovieDbException.MovieDbExceptionType.CONNECTION_ERROR,
                        "No HTTP connection could be made.", url);
            }

            if (isDeleteRequest) {
                cnx.setDoOutput(true);
                cnx.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                cnx.setRequestMethod("DELETE");
            }

            sendHeader(cnx);

            if (StringUtils.isNotBlank(jsonBody)) {
                cnx.setDoOutput(true);
                wr = new OutputStreamWriter(cnx.getOutputStream());
                wr.write(jsonBody);
            }

            readHeader(cnx);

            // http://stackoverflow.com/questions/4633048/httpurlconnection-reading-response-content-on-403-error
            if (cnx.getResponseCode() >= 400) {
                in = new BufferedReader(new InputStreamReader(cnx.getErrorStream(), getCharset(cnx)));
            } else {
                in = new BufferedReader(new InputStreamReader(cnx.getInputStream(), getCharset(cnx)));
            }

            String line;
            while ((line = in.readLine()) != null) {
                content.write(line);
            }
        } finally {
            if (wr != null) {
                wr.flush();
                wr.close();
            }

            if (in != null) {
                in.close();
            }

            if (cnx instanceof HttpURLConnection) {
                ((HttpURLConnection) cnx).disconnect();
            }
        }
        return content.toString();
    } catch (IOException ex) {
        throw new MovieDbException(MovieDbException.MovieDbExceptionType.CONNECTION_ERROR, null, url, ex);
    } finally {
        if (content != null) {
            try {
                content.close();
            } catch (IOException ex) {
                LOG.debug("Failed to close connection: " + ex.getMessage());
            }
        }
    }
}

From source file:com.luke.lukef.lukeapp.tools.LukeNetUtils.java

/**
 * Generic post method for the luke api.
 * @param urlString Url to send the request to
 * @param params Parameters to send with the request as a String
 * @return boolean indicating the success of the request
 *//*from   www .  j ava 2s . c  om*/
private boolean postMethod(String urlString, String params) {
    try {
        HttpURLConnection conn;
        URL url = new URL(urlString);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty(context.getString(R.string.authorization),
                context.getString(R.string.bearer) + SessionSingleton.getInstance().getIdToken());
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("charset", "utf-8");
        conn.setDoOutput(true);

        //get the output stream of the connection
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        //write the JSONobject to the connections output
        writer.write(params);

        //flush and close the writer
        writer.flush();
        writer.close();

        //get the response, if successfull, get inputstream, if unsuccessful get errorStream
        BufferedReader bufferedReader;
        Log.e(TAG, "updateUserImage call: RESPONSE CODE:" + conn.getResponseCode());
        if (conn.getResponseCode() != 200) {
            bufferedReader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));

        } else {
            // TODO: 25/11/2016 check for authorization error, respond accordingly
            bufferedReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        }
        String jsonString;
        StringBuilder stringBuilder = new StringBuilder();
        String line2;
        while ((line2 = bufferedReader.readLine()) != null) {
            stringBuilder.append(line2).append("\n");
        }
        bufferedReader.close();
        jsonString = stringBuilder.toString();
        Log.e(TAG, "updateUserImage run: Result : " + jsonString);
        conn.disconnect();
        return true;
    } catch (IOException e) {
        Log.e(TAG, "postMethod: ", e);
        return false;
    }
}

From source file:TimestreamsTests.java

/**
 * Performs HTTP post for a given URL//from   w  ww  . ja  v a2s  .co  m
 * 
 * @param url
 *            is the URL to get
 * @param params
 *            is a URL encoded string in the form x=y&a=b...
 * @return a String with the contents of the get
 */
private Map<String, List<String>> doPut(URL url, String params) {
    HttpURLConnection connection;
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        connection.setRequestProperty("Content-Length", "" + Integer.toString(params.getBytes().length));

        connection.setDoInput(true);
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(params);
        out.close();
        Map<String, List<String>> responseHeaderFields = connection.getHeaderFields();
        System.out.println(responseHeaderFields);
        if (responseHeaderFields.get(null).get(0).equals("HTTP/1.1 200 OK")) {
            InputStream is = connection.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            while ((line = rd.readLine()) != null) {
                response.append(line);
                response.append('\r');
            }
            rd.close();
            System.out.println(response);
        }
        return responseHeaderFields;
    } catch (IOException e1) {
        fail("Post " + url + " failed: " + e1.getLocalizedMessage());
    }

    return null;
}

From source file:com.kjt.service.common.SoafwTesterMojo.java

private void write(String dest, String template, String tpl) throws MojoExecutionException {
    // FileWriter fw = null;
    OutputStreamWriter osw = null;
    try {//w  ww .  j a v a  2  s .  c  o m
        new File(dest).mkdirs();
        osw = new OutputStreamWriter(new FileOutputStream(dest + File.separator + template), "UTF-8");
        // fw = new FileWriter(dest + File.separator + template);
        osw.write(tpl);
    } catch (IOException e) {
        throw new MojoExecutionException("", e);
    } finally {
        try {
            if (osw != null) {
                osw.close();
            }
        } catch (IOException e) {
        }
    }
}

From source file:by.heap.remark.Main.java

private void convertToFile(Remark remark, Args myArgs) {
    FileOutputStream fos = null;/*from w  w  w. j a va 2s .c o m*/
    OutputStreamWriter osw = null;
    BufferedWriter bw = null;
    try {
        //noinspection IOResourceOpenedButNotSafelyClosed
        fos = new FileOutputStream(myArgs.output);
        //noinspection IOResourceOpenedButNotSafelyClosed
        osw = new OutputStreamWriter(fos, "UTF-8");
        //noinspection IOResourceOpenedButNotSafelyClosed
        bw = new BufferedWriter(osw);
        remark = remark.withWriter(bw);
        convert(remark, myArgs);

    } catch (IOException ex) {
        System.err.println("Error reading from input or writing to output file:");
        System.err.println("  " + ex.getMessage());
    } finally {
        try {
            if (bw != null) {
                bw.close();
            }
            if (osw != null) {
                osw.close();
            }
            if (fos != null) {
                fos.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}