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:org.pegadi.server.article.ArticleServerImpl.java

/**
 * Backup an article as XML/*from w w w. ja  va 2  s. com*/
 *
 * @param articleID The ID of the article.
 * @param text      The text of the article.
 * @return <code>true</code> if all parts of the save operation
 *         was successful.
 */
protected boolean doBackup(int articleID, String text) {
    // Dump the XML to file
    SimpleDateFormat df = new SimpleDateFormat("-yyyyy-MM-dd-HH-mm");
    String xmlFile = backupLocation + "/" + articleID + df.format(new Date()) + ".xml";

    FileOutputStream fos = null;
    OutputStreamWriter writer = null;
    try {
        fos = new FileOutputStream(xmlFile);
        writer = new OutputStreamWriter(fos, Charset.forName("utf-8"));
        writer.write(text);

    } catch (IOException e) {
        log.error("doBackup: Error writing XML file, aborting publish", e);
        log.info("saveArticleText: WARNING: backup failed for article {}!", articleID);
    } finally {
        try {
            if (writer != null)
                writer.close();
            if (fos != null)
                fos.close();
        } catch (IOException e) {
            log.error("Failed on stream close", e);
        }
    }
    log.info("doBackup: XML file saves as '{}'.", xmlFile);

    return true;
}

From source file:debrepo.teamcity.web.DebDownloadController.java

/**
 * Creates a new {@link GZIPOutputStream} and streams the stringToGzip through it to the provided {@link OutputStream}
 * @param stringToGzip - String of text which needs gzipping.
 * @param outputStream - {@link OutputStream} to write gzip'd string to.
 * @throws IOException/*  w  w w.  j  a  v  a 2s.co  m*/
 */
private void gzip(String stringToGzip, OutputStream outputStream) throws IOException {
    GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
    OutputStreamWriter osw = new OutputStreamWriter(gzip, StandardCharsets.UTF_8);
    osw.write(stringToGzip);
    osw.flush();
    osw.close();
}

From source file:com.akop.bach.parser.Parser.java

protected void writeToFile(String filename, String text) {
    java.io.OutputStreamWriter osw = null;

    try {/*from   w ww  . j a  v  a  2s.  com*/
        java.io.FileOutputStream fOut = mContext.openFileOutput(filename, 0666);
        osw = new java.io.OutputStreamWriter(fOut);
        osw.write(text);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (osw != null) {
            try {
                osw.flush();
                osw.close();
            } catch (IOException e) {
            }
        }
    }
}

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
 *//*  w w w .  j  a v a2 s  .c o m*/
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:biblivre3.cataloging.bibliographic.BiblioBO.java

private File createIsoFile(Database database) {
    try {/*  w  w  w . ja  v  a2  s  .co m*/
        File file = File.createTempFile("bib3_", null);
        FileOutputStream fos = new FileOutputStream(file);
        OutputStreamWriter writer = new OutputStreamWriter(fos, "UTF-8");
        BiblioDAO biblioDao = new BiblioDAO();
        int limit = 100;
        int recordCount = biblioDao.countAll(database);

        for (int offset = 0; offset < recordCount; offset += limit) {
            ArrayList<RecordDTO> records = biblioDao.list(database, MaterialType.ALL, offset, limit, false);
            for (RecordDTO 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: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);/*from   w w w.  j a  v  a  2s  . co  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:com.multimedia.service.wallpaper.CmsWallpaperService.java

protected boolean createDescriptionFile(File cur_dir, Long page_id, String page_name, boolean prepared) {
    File description = new File(cur_dir, DESCRIPTION_FILE);
    if (!description.exists()) {
        try {/*  w  w w . j a  v a 2 s .  com*/
            description.createNewFile();
            OutputStreamWriter fos = new OutputStreamWriter(new FileOutputStream(description), "UTF-8");
            fos.write("id=");
            fos.write(String.valueOf(page_id));
            fos.write("\r\nname=");
            fos.write(page_name);
            fos.write("\r\nname_translit=");
            fos.write(FileUtils.toTranslit(page_name));
            if (prepared) {
                fos.write("\r\npre_uploaded=true");
            }
            fos.close();
        } catch (IOException ex) {
            logger.error("", ex);
            return false;
        }
    }
    return true;
}

From source file:edu.utsa.sifter.IndexResource.java

@Path("export")
@GET/*w  w w .  j  a va2 s .  com*/
@Produces({ "text/csv" })
public StreamingOutput getDocExport(@QueryParam("id") final String searchID) throws IOException {
    final SearchResults results = searchID != null ? State.Searches.get(searchID) : null;
    //    System.err.println("exporting results for query " + searchID);

    if (results != null) {
        final IndexInfo info = State.IndexLocations.get(results.IndexID);
        final IndexSearcher searcher = getCommentsSearcher(results.IndexID + "comments-idx", info.Path);
        final BookmarkSearcher markStore = searcher == null ? null : new BookmarkSearcher(searcher, null);

        final ArrayList<Result> docs = results.retrieve(0, results.TotalHits);
        // System.err.println("query export has " + results.TotalHits + " items, size of array is " + hits.size());
        final StreamingOutput stream = new StreamingOutput() {
            public void write(OutputStream output) throws IOException, WebApplicationException {
                final OutputStreamWriter writer = new OutputStreamWriter(output, "UTF-8");
                try {
                    writer.write(
                            "ID,Score,Name,Path,Extension,Size,Modified,Accessed,Created,Cell,CellDistance,Bookmark Created,Bookmark Comment\n");
                    int n = 0;
                    for (Result doc : docs) {
                        if (markStore != null) {
                            markStore.executeQuery(parseQuery(doc.ID, "Docs"));
                            final ArrayList<Bookmark> marks = markStore.retrieve();
                            if (marks == null) {
                                writeRecord(doc, null, writer);
                                ++n;
                            } else {
                                for (Bookmark mark : marks) {
                                    writeRecord(doc, mark, writer);
                                    ++n;
                                }
                            }
                        } else {
                            writeRecord(doc, null, writer);
                            ++n;
                        }
                    }
                    // System.err.println("Streamed out " + n + " items");
                    writer.flush();
                } catch (Exception e) {
                    throw new WebApplicationException(e);
                }
            }
        };
        return stream;
        //      return Response.ok(stream, "text/csv").header("content-disposition","attachment; filename=\"export.csv\"").build();
    } else {
        HttpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }
}

From source file:edu.utsa.sifter.IndexResource.java

@Path("exporthits")
@GET/*from w  ww  .ja v a  2  s .  co m*/
@Produces({ "text/csv" })
public StreamingOutput getHitExport(@QueryParam("id") final String searchID)
        throws IOException, InterruptedException, ExecutionException {
    final SearchResults results = searchID != null ? State.Searches.get(searchID) : null;
    //    System.err.println("exporting results for query " + searchID);

    if (results != null) {
        final IndexInfo info = State.IndexLocations.get(results.IndexID);
        final IndexSearcher searcher = getCommentsSearcher(results.IndexID + "comments-idx", info.Path);
        final BookmarkSearcher markStore = searcher == null ? null : new BookmarkSearcher(searcher, null);

        final ArrayList<SearchHit> hits = results.getSearchHits();
        // System.err.println("query export has " + results.TotalHits + " items, size of array is " + hits.size());
        final StreamingOutput stream = new StreamingOutput() {
            public void write(OutputStream output) throws IOException, WebApplicationException {
                final OutputStreamWriter writer = new OutputStreamWriter(output, "UTF-8");
                try {
                    writer.write(
                            "ID,Score,Name,Path,Extension,Size,Modified,Accessed,Created,Cell,CellDistance,Start,End,Snippet,Bookmark Created,Bookmark Comment\n");
                    int n = 0;
                    for (SearchHit hit : hits) {
                        if (markStore != null) {
                            markStore.executeQuery(parseQuery(hit.ID(), "Docs"));
                            final ArrayList<Bookmark> marks = markStore.retrieve();
                            if (marks == null) {
                                writeHitRecord(hit, null, writer);
                                ++n;
                            } else {
                                for (Bookmark mark : marks) {
                                    writeHitRecord(hit, mark, writer);
                                    ++n;
                                }
                            }
                        } else {
                            writeHitRecord(hit, null, writer);
                            ++n;
                        }
                    }
                    // System.err.println("Streamed out " + n + " items");
                    writer.flush();
                } catch (Exception e) {
                    throw new WebApplicationException(e);
                }
            }
        };
        return stream;
        //      return Response.ok(stream, "text/csv").header("content-disposition","attachment; filename=\"export.csv\"").build();
    } else {
        HttpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }
}

From source file:edu.utsa.sifter.IndexResource.java

@Path("exporthitsFeatures")
@GET//from   www.  j av  a  2  s. c o m
@Produces({ "text/csv" })
public StreamingOutput getHitExportFeatures(@QueryParam("id") final String searchID)
        throws IOException, InterruptedException, ExecutionException {
    final SearchResults results = searchID != null ? State.Searches.get(searchID) : null;
    //    System.err.println("exporting results for query " + searchID);

    if (results != null) {
        final IndexInfo info = State.IndexLocations.get(results.IndexID);
        final IndexSearcher searcher = getCommentsSearcher(results.IndexID + "comments-idx", info.Path);
        final BookmarkSearcher markStore = searcher == null ? null : new BookmarkSearcher(searcher, null);

        final ArrayList<SearchHit> hits = results.getSearchHits();
        // System.err.println("query export has " + results.TotalHits + " items, size of array is " + hits.size());
        final StreamingOutput stream = new StreamingOutput() {
            public void write(OutputStream output) throws IOException, WebApplicationException {
                final OutputStreamWriter writer = new OutputStreamWriter(output, "UTF-8");
                try {
                    writer.write(
                            "ID,Score,Name,Path,Extension,Size,Modified,Accessed,Created,Cell,CellDistance,Start,End,Snippet,Bookmark Created,Bookmark Comment\n");
                    int n = 0;
                    for (SearchHit hit : hits) {
                        if (markStore != null) {
                            markStore.executeQuery(parseQuery(hit.ID(), "Docs"));
                            final ArrayList<Bookmark> marks = markStore.retrieve();
                            if (marks == null) {
                                writeHitRecord(hit, null, writer);
                                ++n;
                            } else {
                                for (Bookmark mark : marks) {
                                    writeHitRecord(hit, mark, writer);
                                    ++n;
                                }
                            }
                        } else {
                            writeHitRecord(hit, null, writer);
                            ++n;
                        }
                    }
                    // System.err.println("Streamed out " + n + " items");
                    writer.flush();
                } catch (Exception e) {
                    throw new WebApplicationException(e);
                }
            }
        };
        return stream;
        //      return Response.ok(stream, "text/csv").header("content-disposition","attachment; filename=\"export.csv\"").build();
    } else {
        HttpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
        return null;
    }
}