Example usage for java.io BufferedWriter newLine

List of usage examples for java.io BufferedWriter newLine

Introduction

In this page you can find the example usage for java.io BufferedWriter newLine.

Prototype

public void newLine() throws IOException 

Source Link

Document

Writes a line separator.

Usage

From source file:edu.uci.ics.jung.io.CustomPajekNetWriter.java

/**
 * Writes <code>graph</code> to <code>w</code>. Labels for vertices may be
 * supplied by <code>vs</code> (defaults to no labels if null), edge weights
 * may be specified by <code>nev</code> (defaults to weights of 1.0 if
 * null), and vertex locations may be specified by <code>vld</code>
 * (defaults to no locations if null)./*from   w  ww . j a v  a 2s. c  o  m*/
 */
public void save(MyGraph<V, E> graph, Writer w, Transformer<V, String> vs, Transformer<E, Number> nev,
        Transformer<V, Point2D> vld) throws IOException {
    /*
     * TODO: Changes we might want to make:
     * - optionally writing out in list form
     */

    BufferedWriter writer = new BufferedWriter(w);
    if (nev == null) {
        nev = new Transformer<E, Number>() {
            public Number transform(E e) {
                return 1;
            }
        };
    }
    writer.write("*Colors " + graph.getLayoutParameters().getBackgroundColorRgb() + ","
            + graph.getLayoutParameters().getEdgeColorRgb());
    writer.newLine();
    writer.write(
            "*Vertices " + graph.getVertexCount() + "," + graph.getLayoutParameters().areNodeIconsAllowed());
    writer.newLine();

    List<V> id = new ArrayList<V>(graph.getVertices());//Indexer.getIndexer(graph);
    for (V currentVertex : graph.getVertices()) {
        // convert from 0-based to 1-based index
        int v_id = id.indexOf(currentVertex) + 1;
        writer.write("" + v_id);
        if (vs != null) {
            String label = vs.transform(currentVertex);
            if (label != null) {
                writer.write(" \"" + label + "\"");
            }
        }
        if (vld != null) {
            Point2D location = vld.transform(currentVertex);
            if (location != null) {
                writer.write(" " + location.getX() + " " + location.getY() + " 0.0");
            }
        }
        writer.newLine();
    }

    Collection<E> d_set = new HashSet<E>();
    Collection<E> u_set = new HashSet<E>();

    boolean directed = graph instanceof DirectedGraph;

    boolean undirected = graph instanceof UndirectedGraph;

    // if it's strictly one or the other, no need to create extra sets
    if (directed) {
        d_set.addAll(graph.getEdges());
    }
    if (undirected) {
        u_set.addAll(graph.getEdges());
    }
    if (!directed && !undirected) // mixed-mode graph
    {
        u_set.addAll(graph.getEdges());
        d_set.addAll(graph.getEdges());
        for (E e : graph.getEdges()) {
            if (graph.getEdgeType(e) == EdgeType.UNDIRECTED) {
                d_set.remove(e);
            } else {
                u_set.remove(e);
            }
        }
    }

    // write out directed edges
    if (!d_set.isEmpty()) {
        writer.write("*Arcs");
        writer.newLine();
    }
    for (E e : d_set) {
        int source_id = id.indexOf(graph.getEndpoints(e).getFirst()) + 1;
        int target_id = id.indexOf(graph.getEndpoints(e).getSecond()) + 1;
        float weight = nev.transform(e).floatValue();
        writer.write(source_id + " " + target_id + " " + weight);
        writer.newLine();
    }

    // write out undirected edges
    if (!u_set.isEmpty()) {
        writer.write("*Edges");
        writer.newLine();
    }
    for (E e : u_set) {
        Pair<V> endpoints = graph.getEndpoints(e);
        int v1_id = id.indexOf(endpoints.getFirst()) + 1;
        int v2_id = id.indexOf(endpoints.getSecond()) + 1;
        float weight = nev.transform(e).floatValue();
        writer.write(v1_id + " " + v2_id + " " + weight);
        writer.newLine();
    }
    writer.close();
}

From source file:playground.artemc.analysis.AnalysisControlerListener.java

private void writeTripAnalysis(IterationEndsEvent event) {

    String tripsFilePath = this.scenario.getConfig().controler().getOutputDirectory() + "/tripsAnalysis.csv";
    File tripsFile = new File(tripsFilePath);

    try {/*from www  . j  a  v a2  s. c o  m*/
        BufferedWriter tripsWriter = new BufferedWriter(new FileWriter(tripsFile));

        tripsWriter.write("Car Trips;Pt Trips;Walk Trips; TrasitWalk Legs");

        tripsWriter.newLine();

        for (Integer it : this.it2userBenefits_selected.keySet()) {
            tripsWriter.write(it + ";" + this.it2carLegs.get(it) + ";" + this.it2ptLegs.get(it) + ";"
                    + this.it2walkLegs.get(it) + ";" + this.it2transitWalkLegs.get(it));

            tripsWriter.newLine();
        }
        tripsWriter.close();
        log.info("Trip analysis Output written to " + tripsFilePath);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.matsim.contrib.analysis.christoph.DistanceDistribution.java

private void writeDistanceDistributionClass(DistributionClass distributionClass, int iteration,
        OutputDirectoryHierarchy outputDirectoryHierarchy) {

    String fileName = outputDirectoryHierarchy.getIterationFilename(iteration,
            "DistanceDistribution_" + distributionClass.name);

    double[] referenceShare = new double[distributionClass.distributionBins.size()];
    double[] simulationShare = new double[distributionClass.distributionBins.size()];

    // accumulate total count
    int count = 0;
    for (DistanceBin distanceBin : distributionClass.distributionBins) {
        count += distanceBin.count;/*from ww w .j a  v  a2s.  co  m*/
    }

    try {
        BufferedWriter writer = IOUtils.getBufferedWriter(fileName + ".txt");
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("low" + "\t");
        stringBuffer.append("high" + "\t");
        stringBuffer.append("reference share" + "\t");
        stringBuffer.append("simulation share");

        writer.write(stringBuffer.toString());
        writer.newLine();

        int i = 0;
        log.info("Distance distribution for class " + distributionClass.name);
        for (DistanceBin distanceBin : distributionClass.distributionBins) {

            referenceShare[i] = distanceBin.referenceShare;
            simulationShare[i] = (double) distanceBin.count / (double) count;

            stringBuffer = new StringBuffer();
            stringBuffer.append(distanceBin.low + "\t");
            stringBuffer.append(distanceBin.high + "\t");
            stringBuffer.append(distanceBin.referenceShare + "\t");
            stringBuffer.append(String.valueOf(simulationShare[i]));

            log.info("\t" + stringBuffer.toString());

            writer.write(stringBuffer.toString());
            writer.newLine();

            i++;
        }
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    String title = "Distance distribution for class " + distributionClass.name;
    String xAxisLabel = "Distance class";
    String yAxisLabel = "Share";
    String[] categories = new String[distributionClass.distributionBins.size()];
    int i = 0;
    for (DistanceBin distanceBin : distributionClass.distributionBins) {
        categories[i++] = distanceBin.low + "\n" + " .. " + "\n" + distanceBin.high;
    }
    BarChart chart = new BarChart(title, xAxisLabel, yAxisLabel, categories);

    CategoryPlot plot = chart.getChart().getCategoryPlot();
    CategoryAxis categoryAxis = plot.getDomainAxis();
    categoryAxis.setMaximumCategoryLabelLines(3);

    chart.addMatsimLogo();
    chart.addSeries("reference share", referenceShare);
    chart.addSeries("simulation share", simulationShare);
    chart.saveAsPng(fileName + ".png", 1024, 768);
}

From source file:com.roamtouch.menuserver.utils.FileUtils.java

public void storeAboutLog(String text) {

    File logFolder = new File(app.getSDCARD() + "/httpd/media/about");
    if (!logFolder.exists()) {
        logFolder.mkdir();/* w  w w  .jav a 2s . c  o m*/
    }

    String dateFormat = app.getTimeDate("dd_MM_yyyy");

    File logFile = new File(
            logFolder.toString() + "/" + "About_" + getWeekDay() + "-" + dateFormat + "" + ".txt");
    if (!logFile.exists()) {
        try {
            logFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
        buf.append(text);
        buf.newLine();
        buf.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.lines.activitys.SettingsActivity.java

/**
 * Update the Settings file with the user's selections
 * /*ww  w.  j  a  v  a 2s.  com*/
 */
private void saveSettings() {
    File settings = new File(Environment.getExternalStorageDirectory() + "/learnyourlines/.settings.sav");
    if (settings.exists()) {
        settings.delete();
    }

    FileWriter fileWriter;
    BufferedWriter writer;

    try {
        fileWriter = new FileWriter(settings);
        writer = new BufferedWriter(fileWriter);

        writer.write(mScripts.getSelectedItem().toString());
        writer.newLine();
        writer.write(mPrompts.getSelectedItem().toString());
        writer.newLine();
        writer.write(mAuto.getSelectedItem().toString());
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    Toast.makeText(getApplicationContext(), "Settings saved!", Toast.LENGTH_LONG).show();
}

From source file:edu.nd.darts.cimon.MonitorReport.java

/**
 * Generate monitor report and store on SD card.
 * //from   ww w .  ja v a  2 s .c  o m
 * @return true if file successfully created
 */
private boolean createFile() {

    if (DebugLog.DEBUG)
        Log.d(TAG, "MonitorReport - createFile:" + monitorId + " metric:" + metricId);
    String state = Environment.getExternalStorageState();
    if (!Environment.MEDIA_MOUNTED.equals(state)) {
        if (DebugLog.WARNING)
            Log.w(TAG, "MonitorReport.createFile - external storage not available");
        return false;
    }
    File file = new File(context.getExternalFilesDir(null), "monitor" + monitorId + ".csv");
    BufferedWriter writer;
    try {
        writer = new BufferedWriter(new FileWriter(file));

        if (metadata) {
            writer.write("sep=\t");
            writer.newLine();
            Uri metricUri = Uri.withAppendedPath(CimonContentProvider.METRICS_URI, String.valueOf(metricId));
            Cursor metricCursor = context.getContentResolver().query(metricUri, null, null, null, null);
            if (metricCursor == null) {
                if (DebugLog.WARNING)
                    Log.w(TAG, "MonitorReport.createFile - metric cursor is empty");
            } else {
                int nameCol = metricCursor.getColumnIndex(MetricsTable.COLUMN_METRIC);
                int unitsCol = metricCursor.getColumnIndex(MetricsTable.COLUMN_UNITS);
                if (metricCursor.moveToFirst()) {
                    if (nameCol < 0) {
                        if (DebugLog.WARNING)
                            Log.w(TAG, "MonitorReport.createFile - metric name column not found");
                    } else {
                        metricName = metricCursor.getString(nameCol);
                    }
                    writer.write("Metric: " + metricName);
                    writer.newLine();

                    if (unitsCol < 0) {
                        if (DebugLog.WARNING)
                            Log.w(TAG, "MonitorReport.createFile - metric name column not found");
                    } else {
                        String units = metricCursor.getString(unitsCol);
                        writer.write("Units: " + units);
                        writer.newLine();
                    }
                } else {
                    if (DebugLog.WARNING)
                        Log.w(TAG, "MonitorReport.createFile - metric cursor empty");
                }
            }
            metricCursor.close();

            Uri monitorUri = Uri.withAppendedPath(CimonContentProvider.MONITOR_URI, String.valueOf(monitorId));
            Cursor monitorCursor = context.getContentResolver().query(monitorUri, null, null, null, null);
            if (monitorCursor == null) {
                if (DebugLog.WARNING)
                    Log.w(TAG, "MonitorReport.createFile - monitor cursor is empty");
            } else {
                int offsetCol = monitorCursor.getColumnIndex(MonitorTable.COLUMN_TIME_OFFSET);
                if (monitorCursor.moveToFirst()) {
                    if (offsetCol < 0) {
                        if (DebugLog.WARNING)
                            Log.w(TAG, "MonitorReport.createFile - epoch offset column not found");
                    } else {
                        long offset = monitorCursor.getLong(offsetCol);
                        writer.write("Offset from epoch (milliseconds): " + offset);
                        writer.newLine();
                    }
                } else {
                    if (DebugLog.WARNING)
                        Log.w(TAG, "MonitorReport.createFile - monitor cursor empty");
                }
            }
            monitorCursor.close();

            writer.newLine();
        }
        writer.write("Timestamp\tValue");
        writer.newLine();

        String[] projection = { DataTable.COLUMN_TIMESTAMP, DataTable.COLUMN_VALUE };
        Uri monitorUri = Uri.withAppendedPath(CimonContentProvider.MONITOR_DATA_URI, String.valueOf(monitorId));
        Cursor mCursor = context.getContentResolver().query(monitorUri, projection, null, null, null);
        if (mCursor == null) {
            if (DebugLog.WARNING)
                Log.w(TAG, "MonitorReport.createFile - data cursor is empty");
            writer.close();
            return false;
        }
        int timestampCol = mCursor.getColumnIndex(DataTable.COLUMN_TIMESTAMP);
        if (timestampCol < 0) {
            if (DebugLog.WARNING)
                Log.w(TAG, "MonitorReport.createFile - timestamp column not found");
            mCursor.close();
            writer.close();
            return false;
        }
        int valueCol = mCursor.getColumnIndex(DataTable.COLUMN_VALUE);
        if (valueCol < 0) {
            if (DebugLog.WARNING)
                Log.w(TAG, "MonitorReport.createFile - value column not found");
            mCursor.close();
            writer.close();
            return false;
        }
        long timestamp;
        float value;
        if (mCursor.moveToFirst()) {
            while (!mCursor.isAfterLast()) {
                timestamp = mCursor.getLong(timestampCol);
                value = mCursor.getFloat(valueCol);
                writer.write(timestamp + "\t" + value);
                writer.newLine();
                mCursor.moveToNext();
            }
        }
        mCursor.close();

        writer.flush();
        writer.close();
    } catch (IOException e) {
        if (DebugLog.WARNING)
            Log.w(TAG, "MonitorReport.createFile - file writer failed");
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.yifanlu.PSXperiaTool.StringReplacement.java

public void replaceStringsIn(File file) throws IOException {
    String name = file.getPath();
    BufferedReader reader = new BufferedReader(new FileReader(file));
    BufferedWriter writer = new BufferedWriter(new FileWriter(name + ".tmp"));
    Logger.debug("Writing to temporary file: %s", name + ".tmp");
    String line;// w  ww  .  ja v  a2 s . co  m
    while ((line = reader.readLine()) != null) {
        Logger.verbose("Data line before replacement: %s", line);
        Iterator<String> keys = mMap.keySet().iterator();
        while (keys.hasNext()) {
            String key = keys.next();
            String value = mMap.get(key);
            line = line.replaceAll(key, value);
        }
        Logger.verbose("Data line after replacement: %s", line);
        writer.write(line);
        writer.newLine();
    }
    reader.close();
    writer.close();
    file.delete();
    FileUtils.moveFile(new File(name + ".tmp"), file);
    Logger.debug("Successfully cleaned up and done with string replacement.");
}

From source file:com.ideateam.plugin.Version.java

public void writeLocaleToFile(String fileName, String msg) {

    try {//  ww w. j  a  v a  2s  .  c o  m
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/TSVB/" + fileName;

        File file = new File(path);

        if (!file.exists()) {
            File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/TSVB/");
            f.mkdirs();
            file.createNewFile();

        }

        BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
        buf.append(msg);
        buf.newLine();
        buf.close();
        // callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, "writed to file"));
        Log.d(TAG, "..callBackPlugin");
        activity.sendJavascript("TSVB.system.Helper.callBackPlugin('ok')");

    } catch (IOException e) {
        Log.d(TAG, e.getMessage());
    }

}

From source file:nz.co.jsrsolutions.ds3.sink.CsvEodDataSink.java

public void updateExchangeSymbolQuotes(String exchange, String symbol, QUOTE[] quotes)
        throws EodDataSinkException {

    try {/*from w ww.j a v  a  2s  .  c o  m*/

        StringBuffer filenameBuf = new StringBuffer();
        filenameBuf.append("/data/eoddata/");
        filenameBuf.append(exchange);
        filenameBuf.append("/");
        filenameBuf.append(symbol);
        filenameBuf.append("/");
        filenameBuf.append(exchange);
        filenameBuf.append(".");
        filenameBuf.append(symbol);
        //      filenameBuf.append(".");
        //      filenameBuf.append(startDate);
        //      filenameBuf.append("-");
        //      filenameBuf.append(endDate);
        //      filenameBuf.append(".");
        //      filenameBuf.append(period);
        filenameBuf.append(".csv");

        String filename = new String(filenameBuf.toString());

        StringBuffer infoMessage = new StringBuffer();
        infoMessage.append("Writing output to: [ ");
        infoMessage.append(filename);
        infoMessage.append(" ] ");
        logger.info(infoMessage.toString());

        FileWriter fileWriter = new FileWriter(filenameBuf.toString());
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

        for (DataStub.QUOTE quote : quotes) {

            Calendar calendar = quote.getDateTime();
            bufferedWriter.append(Integer.toString(calendar.get(Calendar.YEAR)));
            bufferedWriter.append(String.format("%02d", calendar.get(Calendar.MONTH)));
            bufferedWriter.append(String.format("%02d", calendar.get(Calendar.DAY_OF_MONTH)));
            bufferedWriter.append(",");
            bufferedWriter.append(Double.toString(quote.getClose()));
            bufferedWriter.newLine();

        }

        bufferedWriter.close();

    } catch (java.io.IOException ioe) {

        logger.error(ioe.toString());
        EodDataSinkException edpe = new EodDataSinkException("Unable to set symbols");
        edpe.initCause(ioe);

        throw edpe;

    }
}

From source file:com.careerly.common.support.msgconverter.CsvHttpMessageConverter.java

@Override
protected void writeInternal(CsvResponse t, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {
    ServletServerHttpResponse response = (ServletServerHttpResponse) outputMessage;
    response.getServletResponse().setCharacterEncoding("UTF-8");
    outputMessage.getHeaders().set("Content-Disposition", "attachment; filename=\"" + t.getFileName() + "\"");
    BufferedWriter bw = new BufferedWriter(
            new OutputStreamWriter(outputMessage.getBody(), Charset.forName("UTF-8")));
    try {/*w  ww  .j  a v a2  s .  c o  m*/
        for (List<String> line : Iterables.concat(Collections.singleton(t.getHead()), t.getBody())) {
            for (int i = 0; i < line.size(); i++) {
                if (line.get(i) != null) {
                    bw.write("\"");
                    bw.write(line.get(i));
                    bw.write("\"");
                }
                if (i < line.size() - 1) {
                    bw.write(seperator);
                }
            }
            bw.newLine();
        }
    } finally {
        bw.close();
    }
}