Example usage for java.io BufferedWriter flush

List of usage examples for java.io BufferedWriter flush

Introduction

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

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes the stream.

Usage

From source file:com.github.braully.graph.BatchExecuteOperation.java

public void processStreamGraph(BufferedReader r, IGraphOperation operation, String dirname,
        String graphFileName, BufferedWriter writer, long continueOffset) throws IOException {
    long graphcount = 0;
    String readLine;//  w w w .ja  va  2  s .c o m
    while ((readLine = r.readLine()) != null && !readLine.isEmpty()) {
        try {
            UndirectedSparseGraphTO ret = UtilGraph.loadGraphG6(readLine);
            if (ret != null) {
                if (graphcount > continueOffset) {
                    ret.setName(graphFileName + "-" + graphcount);
                    String resultProcess = processGraph(operation, ret, dirname, graphcount);
                    writer.write(resultProcess);
                    writer.flush();
                    if (verbose) {
                        System.out.println(resultProcess);
                    }
                }
                graphcount++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.imaginary.home.controller.HomeController.java

private void saveConfiguration() throws ControllerException {
    ArrayList<Map<String, Object>> all = new ArrayList<Map<String, Object>>();
    HashMap<String, Object> cfg = new HashMap<String, Object>();

    cfg.put("name", name);
    for (HomeAutomationSystem sys : listSystems()) {
        HashMap<String, Object> json = new HashMap<String, Object>();

        json.put("cname", sys.getClass().getName());
        json.put("id", sys.getId());
        json.put("authenticationProperties", sys.getAuthenticationProperties());
        json.put("customProperties", sys.getCustomProperties());
        all.add(json);/*  w w  w . j av  a 2  s .  co  m*/
    }
    cfg.put("systems", all);
    all = new ArrayList<Map<String, Object>>();
    for (CloudService service : cloudServices) {
        HashMap<String, Object> json = new HashMap<String, Object>();

        json.put("id", service.getServiceId());
        json.put("name", service.getName());
        json.put("endpoint", service.getEndpoint());
        json.put("apiKeySecret", service.getApiKeySecret());
        if (service.getProxyHost() != null) {
            json.put("proxyHost", service.getProxyHost());
            json.put("proxyPort", service.getProxyPort());
        }
        all.add(json);
    }
    cfg.put("services", all);
    try {
        File f = new File(CONFIG_FILE);
        File backup = null;

        if (f.exists()) {
            backup = new File(CONFIG_FILE + "." + System.currentTimeMillis());
            if (!f.renameTo(backup)) {
                throw new ControllerException("Unable to make backup of configuration file");
            }
            f = new File(CONFIG_FILE);
        }
        boolean success = false;
        try {
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f)));

            writer.write((new JSONObject(cfg)).toString());
            writer.newLine();
            writer.flush();
            writer.close();
            success = true;
        } finally {
            if (!success && backup != null) {
                //noinspection ResultOfMethodCallIgnored
                backup.renameTo(f);
            }
        }
    } catch (IOException e) {
        throw new ControllerException("Unable to save configuration: " + e.getMessage());
    }
}

From source file:com.imaginary.home.controller.HomeController.java

private void saveCommands(List<CommandList> toSave) throws ControllerException {
    synchronized (commandQueue) {
        ArrayList<Map<String, Object>> all = new ArrayList<Map<String, Object>>();
        HashMap<String, Object> cfg = new HashMap<String, Object>();

        for (CommandList cmdList : toSave) {
            ArrayList<Map<String, Object>> commands = new ArrayList<Map<String, Object>>();
            HashMap<String, Object> map = new HashMap<String, Object>();

            for (JSONObject cmd : cmdList) {
                try {
                    commands.add(toMap(cmd));
                } catch (JSONException e) {
                    throw new ControllerException(e);
                }//  www . ja  v  a2 s.c om
            }
            map.put("commands", commands);
            map.put("serviceId", cmdList.getServiceId());
            all.add(map);
        }
        cfg.put("commands", all);
        try {
            File f = new File(COMMAND_FILE);
            File backup = null;

            if (f.exists()) {
                backup = new File(COMMAND_FILE + "." + System.currentTimeMillis());
                if (!f.renameTo(backup)) {
                    throw new ControllerException("Unable to make backup of configuration file");
                }
                f = new File(COMMAND_FILE);
            }
            boolean success = false;
            try {
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f)));

                writer.write((new JSONObject(cfg)).toString());
                writer.newLine();
                writer.flush();
                writer.close();
                success = true;
            } finally {
                if (!success && backup != null) {
                    //noinspection ResultOfMethodCallIgnored
                    backup.renameTo(f);
                }
            }
        } catch (IOException e) {
            throw new ControllerException("Unable to save command file: " + e.getMessage());
        }
    }
}

From source file:net.sibcolombia.sibsp.service.portal.implementation.SourceManagerImplementation.java

@Override
public String analyze(Source source) {
    String problem = null;/*w w  w.j av a2 s  .  c  om*/
    if (source instanceof FileSource) {
        FileSource fs = (FileSource) source;
        try {
            CSVReader reader = fs.getReader();
            fs.setFileSize(fs.getFile().length());
            // careful - the reader.header can be null. In this case set number of columns to 0
            fs.setColumns((reader.header == null) ? 0 : reader.header.length);
            while (reader.hasNext()) {
                reader.next();
            }
            fs.setRows(reader.getReadRows());
            fs.setReadable(true);

            File logFile = dataDir.sourceLogFile(source.getResource().getUniqueID().toString(),
                    source.getName());
            FileUtils.deleteQuietly(logFile);
            BufferedWriter logWriter = null;
            try {
                logWriter = new BufferedWriter(new FileWriter(logFile));
                logWriter.write("Log for source name:" + source.getName() + " from resource: "
                        + source.getResource().getUniqueID().toString() + "\n");
                if (!reader.getEmptyLines().isEmpty()) {
                    List<Integer> emptyLines = new ArrayList<Integer>(reader.getEmptyLines());
                    Collections.sort(emptyLines);
                    for (Integer i : emptyLines) {
                        logWriter.write("Line: " + i + " [EMPTY LINE]\n");
                    }
                } else {
                    logWriter.write("No rows were skipped in this source");
                }
                logWriter.flush();
            } catch (IOException e) {
                log.warn("Cant write source log file " + logFile.getAbsolutePath(), e);
            } finally {
                if (logWriter != null) {
                    logWriter.flush();
                    IOUtils.closeQuietly(logWriter);
                }
            }
        } catch (IOException e) {
            problem = e.getMessage();
            log.warn("Cant read source file " + fs.getFile().getAbsolutePath(), e);
            fs.setReadable(false);
            fs.setRows(-1);
        }

    }
    return problem;
}

From source file:com.google.code.maven.plugin.http.client.transformer.JiraRssLinkedIssuesEnricher.java

@Override
protected Resource doTransform(Resource input) throws Exception {
    Assert.notNull(input, "source can not be null");
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(new FileInputStream(input.getFile()), charset));
    if (target.getFile().getParentFile() != null && !target.getFile().getParentFile().exists()) {
        Assert.isTrue(target.getFile().getParentFile().mkdirs(),
                "failed to make directory tree for [" + target.getFile().getParentFile() + "]");
    }// www  . ja v a  2  s . c  o  m
    String line;
    StringBuilder item = new StringBuilder();
    BufferedWriter writer = new BufferedWriter(new FileWriter(target.getFile()));
    // read rss and find jira links
    while ((line = reader.readLine()) != null) {
        if (line.contains(CHANNEL_END_TAG)) {
            break;
        }
        if (line.contains(ITEM_END_TAG)) {
            item.append(line.substring(0, line.indexOf(ITEM_END_TAG)));
            linkedIssues.addAll(inspectItem(item.toString()));
        }
        if (line.contains(ITEM_START_TAG)) {
            item = new StringBuilder();
            item.append(line.substring(line.indexOf(ITEM_START_TAG)));
        } else {
            item.append(line).append("\n");
        }
        writer.write(line);
        writer.newLine();
        writer.flush();
    }
    enrich(writer, linkedIssues, depth - 1);
    while (remaining.get() > 0) {
        Thread.sleep(100);
    }
    // write end of rss
    do {
        writer.write(line);
    } while ((line = reader.readLine()) != null);
    reader.close();
    writer.close();
    if (deleteSource) {
        Assert.isTrue(input.getFile().delete(), "failed to delete source");
    }
    return target;
}

From source file:com.imaginary.home.controller.HomeController.java

private void saveSchedule() throws ControllerException {
    synchronized (commandQueue) {
        ArrayList<Map<String, Object>> all = new ArrayList<Map<String, Object>>();
        HashMap<String, Object> cfg = new HashMap<String, Object>();

        for (ScheduledCommandList sList : scheduler) {
            ArrayList<Map<String, Object>> commands = new ArrayList<Map<String, Object>>();
            HashMap<String, Object> schedule = new HashMap<String, Object>();

            for (JSONObject cmd : sList) {
                try {
                    commands.add(toMap(cmd));
                } catch (JSONException e) {
                    throw new ControllerException(e);
                }//www .  j  ava2s.  c  o  m
            }
            schedule.put("commands", commands);
            schedule.put("executeAfter", sList.getExecuteAfter());
            schedule.put("scheduleId", sList.getScheduleId());
            schedule.put("serviceId", sList.getServiceId());
            all.add(schedule);
        }
        cfg.put("schedule", all);
        try {
            File f = new File(SCHEDULER_FILE);
            File backup = null;

            if (f.exists()) {
                backup = new File(SCHEDULER_FILE + "." + System.currentTimeMillis());
                if (!f.renameTo(backup)) {
                    throw new ControllerException("Unable to make backup of configuration file");
                }
                f = new File(SCHEDULER_FILE);
            }
            boolean success = false;
            try {
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f)));

                writer.write((new JSONObject(cfg)).toString());
                writer.newLine();
                writer.flush();
                writer.close();
                success = true;
            } finally {
                if (!success && backup != null) {
                    //noinspection ResultOfMethodCallIgnored
                    backup.renameTo(f);
                }
            }
        } catch (IOException e) {
            throw new ControllerException("Unable to save command file: " + e.getMessage());
        }
    }
}

From source file:org.matsim.contrib.analysis.vsp.traveltimedistance.TravelTimeValidationRunner.java

private void writeTravelTimeValidation(String folder, List<CarTrip> trips) {
    BufferedWriter bw = IOUtils.getBufferedWriter(folder + "/validated_trips.csv");
    XYSeriesCollection times = new XYSeriesCollection();
    XYSeriesCollection distances = new XYSeriesCollection();

    XYSeries distancess = new XYSeries("distances", true, true);
    XYSeries timess = new XYSeries("times", true, true);
    times.addSeries(timess);//from   w ww.j a  v  a 2  s . c  o m
    distances.addSeries(distancess);
    try {
        bw.append(
                "agent;departureTime;fromX;fromY;toX;toY;traveltimeActual;traveltimeValidated;traveledDistance;validatedDistance");
        for (CarTrip trip : trips) {
            if (trip.getValidatedTravelTime() != null) {
                bw.newLine();
                bw.append(trip.toString());
                timess.add(trip.getActualTravelTime(), trip.getValidatedTravelTime());
                distancess.add(trip.getTravelledDistance(), trip.getValidatedTravelDistance());
            }
        }

        bw.flush();
        bw.close();
        final JFreeChart chart2 = ChartFactory.createScatterPlot("Travel Times", "Simulated travel time [s]",
                "Validated travel time [s]", times);
        final JFreeChart chart = ChartFactory.createScatterPlot("Travel Distances",
                "Simulated travel distance [m]", "Validated travel distance [m]", distances);

        NumberAxis yAxis = (NumberAxis) ((XYPlot) chart2.getPlot()).getRangeAxis();
        NumberAxis xAxis = (NumberAxis) ((XYPlot) chart2.getPlot()).getDomainAxis();
        NumberAxis yAxisd = (NumberAxis) ((XYPlot) chart.getPlot()).getRangeAxis();
        NumberAxis xAxisd = (NumberAxis) ((XYPlot) chart.getPlot()).getDomainAxis();
        yAxisd.setUpperBound(xAxisd.getUpperBound());
        yAxis.setUpperBound(xAxis.getUpperBound());
        yAxis.setTickUnit(new NumberTickUnit(500));
        xAxis.setTickUnit(new NumberTickUnit(500));

        XYAnnotation diagonal = new XYLineAnnotation(xAxis.getRange().getLowerBound(),
                yAxis.getRange().getLowerBound(), xAxis.getRange().getUpperBound(),
                yAxis.getRange().getUpperBound());
        ((XYPlot) chart2.getPlot()).addAnnotation(diagonal);

        XYAnnotation diagonald = new XYLineAnnotation(xAxisd.getRange().getLowerBound(),
                yAxisd.getRange().getLowerBound(), xAxisd.getRange().getUpperBound(),
                yAxisd.getRange().getUpperBound());
        ((XYPlot) chart.getPlot()).addAnnotation(diagonald);

        ChartUtilities.writeChartAsPNG(new FileOutputStream(folder + "/validated_traveltimes" + ".png"), chart2,
                1500, 1500);
        ChartUtilities.writeChartAsPNG(new FileOutputStream(folder + "/validated_traveldistances.png"), chart,
                1500, 1500);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:canreg.client.analysis.Tools.java

/**
 *
 * @param popoutput//from   ww  w. j a va2 s  . c om
 * @param startYear
 * @param populations
 * @param separator
 * @throws IOException
 * @throws canreg.common.database.IncompatiblePopulationDataSetException
 */
public static void writePopulationsToFile(BufferedWriter popoutput, int startYear,
        PopulationDataset[] populations, String separator)
        throws IOException, IncompatiblePopulationDataSetException {
    String popheader = "YEAR" + separator;
    popheader += "AGE_GROUP_LABEL" + separator;
    popheader += "AGE_GROUP" + separator;
    popheader += "SEX" + separator;
    popheader += "COUNT" + separator;
    popheader += "REFERENCE_COUNT" + separator;
    popheader += "AGE_GROUP_SIZE";
    popoutput.append(popheader);
    popoutput.newLine();
    int thisYear = startYear;
    for (PopulationDataset popset : populations) {
        if (popset != null) {
            String[] ageGroupNames = popset.getAgeGroupStructure().getAgeGroupNames();
            for (PopulationDatasetsEntry pop : popset.getAgeGroups()) {
                popoutput.append(thisYear + "").append(separator);
                popoutput.append(ageGroupNames[pop.getAgeGroup()]).append(separator);
                popoutput.append(pop.getStringRepresentationOfAgeGroupsForFile(separator)).append(separator);
                // get reference pop
                popoutput.append(
                        popset.getReferencePopulationForAgeGroupIndex(pop.getSex(), pop.getAgeGroup()) + "")
                        .append(separator);
                popoutput
                        .append(popset.getAgeGroupStructure().getSizeOfAgeGroupByIndex(pop.getAgeGroup()) + "");
                popoutput.newLine();
            }
        }
        thisYear++;
    }
    popoutput.flush();
}

From source file:com.apkbus.mobile.utils.ACache.java

public void putNewThread(final String key, final String value) {
    new Thread(new Runnable() {
        @Override//w w  w .  ja v  a 2s. co m
        public void run() {
            File file = mCache.newFile(key);
            BufferedWriter out = null;
            try {
                out = new BufferedWriter(new FileWriter(file), 1024);
                out.write(value);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (out != null) {
                    try {
                        out.flush();
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                mCache.put(file);
            }
        }
    }).start();
}

From source file:com.github.geequery.codegen.ast.JavaUnit.java

/**
 * ?SourceFolder//  w  w w.j ava2s  .  co  m
 * @param srcFolder
 * @return
 * @throws IOException
 */
public File saveToSrcFolder(File srcFolder, Charset charset, OverWrittenMode mode) throws IOException {
    File javaFile = new File(srcFolder.getAbsolutePath(), getFilePath());
    if (javaFile.exists()) {
        if (mode == OverWrittenMode.NO)
            return null;
        if (mode == OverWrittenMode.AUTO) {
            if (!protectMode && GenUtil.isModified(javaFile)) {
                // ?????
                return null;
            }
        }
    }
    BufferedWriter bw = IOUtils.getWriter(javaFile, charset == null ? Charset.defaultCharset() : charset,
            false);
    writeTo(bw);
    bw.flush();
    bw.close();
    return javaFile;
}