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.nordicsemi.nrfUARTv2.MainActivity.java

private void generateNoteOnSD(String sFileName, String sBody) {
    File root = new File(Environment.getExternalStorageDirectory(), "Sensors");
    if (!root.exists()) {
        root.mkdirs();//from w  w  w  .  j av a2 s  .  c  o m
    }
    File gpxfile = new File(root, sFileName);
    try {
        BufferedWriter bW;
        bW = new BufferedWriter(new FileWriter(gpxfile, true));
        bW.write(sBody);
        bW.newLine();
        bW.flush();
        bW.close();
    } catch (IOException e) {

    }
}

From source file:de.tudarmstadt.ukp.dkpro.spelling.experiments.errormining.SpellingErrorFilter.java

private void writeItem(BufferedWriter writer, DatasetItem item) throws AnalysisEngineProcessException {
    try {// w w  w  .  j a v  a  2 s  . c  om
        writer.write(item.toString());
        writer.newLine();
        writer.flush();
    } catch (IOException e) {
        throw new AnalysisEngineProcessException(e);
    }
}

From source file:com.sliit.normalize.NormalizeDataset.java

public int whiteningData() {
    System.out.println("whiteningData");

    int nums = 0;
    try {//from   w w  w  . j  a v a 2  s .c om

        if (tempFIle != null && tempFIle.exists()) {

            csv.setSource(tempFIle);
        } else {

            csv.setSource(csvFile);
        }
        Instances instances = csv.getDataSet();
        if (instances.numAttributes() > 10) {
            instances.setClassIndex(instances.numAttributes() - 1);
            RandomProjection random = new RandomProjection();
            random.setDistribution(
                    new SelectedTag(RandomProjection.GAUSSIAN, RandomProjection.TAGS_DSTRS_TYPE));
            reducedDiemensionFile = new File(csvFile.getParent() + "/tempwhite.csv");
            if (!reducedDiemensionFile.exists()) {

                reducedDiemensionFile.createNewFile();
            }
            // CSVSaver saver = new CSVSaver();
            /// saver.setFile(reducedDiemensionFile);
            random.setInputFormat(instances);
            //saver.setRetrieval(AbstractSaver.INCREMENTAL);
            BufferedWriter writer = new BufferedWriter(new FileWriter(reducedDiemensionFile));
            for (int i = 0; i < instances.numInstances(); i++) {

                random.input(instances.instance(i));
                random.setNumberOfAttributes(10);
                random.setReplaceMissingValues(true);
                writer.write(random.output().toString());
                writer.newLine();
                //saver.writeIncremental(random.output());
            }
            writer.flush();
            writer.close();
            nums = random.getNumberOfAttributes();
        } else {

            nums = instances.numAttributes();
        }
    } catch (IOException e) {

        log.error("Error occurred:" + e.getMessage());
    } catch (Exception e) {

        log.error("Error occurred:" + e.getMessage());
    }
    return nums;
}

From source file:com.github.seqware.queryengine.system.exporters.VCFDumper.java

/**
 * <p>dumpVCFFromFeatureSetID.</p>
 *
 * @param fSet a {@link com.github.seqware.queryengine.model.FeatureSet} object.
 * @param file a {@link java.lang.String} object.
 *//*  w w  w  . j  av  a  2 s .c  o m*/
public static void dumpVCFFromFeatureSetID(FeatureSet fSet, String file) {
    BufferedWriter outputStream = null;

    try {
        if (file != null) {
            outputStream = new BufferedWriter(new FileWriter(file));
        } else {
            outputStream = new BufferedWriter(new OutputStreamWriter(System.out));
        }
        outputStream.append("#CHROM   POS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\n");
    } catch (IOException e) {
        Logger.getLogger(VCFDumper.class.getName()).fatal("Exception thrown starting export to file:", e);
        System.exit(-1);
    }

    boolean caughtNonVCF = false;
    boolean mrSuccess = false;
    if (SWQEFactory.getQueryInterface() instanceof MRHBasePersistentBackEnd) {
        // hack to use VCF MR
        if (SWQEFactory.getModelManager() instanceof MRHBaseModelManager) {
            try {
                // pretend that the included com.github.seqware.queryengine.plugins.hbasemr.MRFeaturesByAttributesPlugin is an external plug-in
                Class<? extends PluginInterface> arbitraryPlugin;
                arbitraryPlugin = VCFDumperPlugin.class;
                // get a FeatureSet from the back-end
                QueryFuture<File> future = SWQEFactory.getQueryInterface().getFeaturesByPlugin(0,
                        arbitraryPlugin, fSet);
                File get = future.get();
                BufferedReader in = new BufferedReader(new FileReader(get));
                IOUtils.copy(in, outputStream);
                in.close();
                get.deleteOnExit();
                outputStream.flush();
                outputStream.close();
                mrSuccess = true;
            } catch (IOException e) {
                // fail out on IO error
                Logger.getLogger(VCFDumper.class.getName()).fatal("Exception thrown exporting to file:", e);
                System.exit(-1);
            } catch (Exception e) {
                Logger.getLogger(VCFDumper.class.getName())
                        .info("MapReduce exporting failed, falling-through to normal exporting to file");
                // fall-through and do normal exporting if Map Reduce exporting fails
            }
        } // TODO: clearly this should be expanded to include closing database etc 
    }
    if (mrSuccess) {
        return;
    }
    // fall-through if plugin-fails
    try {
        for (Feature feature : fSet) {
            StringBuffer buffer = new StringBuffer();
            boolean caught = outputFeatureInVCF(buffer, feature);
            if (caught) {
                caughtNonVCF = true;
            }
            outputStream.append(buffer);
            outputStream.newLine();
        }
        outputStream.flush();
    } catch (IOException e) {
        Logger.getLogger(VCFDumper.class.getName()).fatal("Exception thrown exporting to file:", e);
        System.exit(-1);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }
}

From source file:com.alibaba.jstorm.yarn.JstormOnYarn.java

/**
 * Monitor the submitted application for completion.
 * Kill application if time expires.//ww w. j  a va2  s.co  m
 *
 * @param appId Application Id of application to be monitored
 * @return true if application completed successfully
 * @throws YarnException
 * @throws IOException
 */
private boolean monitorApplication(ApplicationId appId) throws YarnException, IOException {

    Integer monitorTimes = JOYConstants.MONITOR_TIMES;

    while (true) {

        // Check app status every 1 second.
        try {
            Thread.sleep(JOYConstants.MONITOR_TIME_INTERVAL);
        } catch (InterruptedException e) {
            LOG.debug("Thread sleep in monitoring loop interrupted");
        }
        // Get application report for the appId we are interested in
        ApplicationReport report = jstormClientContext.yarnClient.getApplicationReport(appId);

        try {
            File writename = new File(JOYConstants.RPC_ADDRESS_FILE);
            writename.createNewFile();
            BufferedWriter out = new BufferedWriter(new FileWriter(writename));
            out.write(report.getHost() + JOYConstants.NEW_LINE);
            out.write(report.getRpcPort() + JOYConstants.NEW_LINE);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        LOG.info("Got application report from ASM for" + ", appId=" + appId.getId() + ", clientToAMToken="
                + report.getClientToAMToken() + ", appDiagnostics=" + report.getDiagnostics()
                + ", appMasterHost=" + report.getHost() + ", appQueue=" + report.getQueue()
                + ", appMasterRpcPort=" + report.getRpcPort() + ", appStartTime=" + report.getStartTime()
                + ", yarnAppState=" + report.getYarnApplicationState().toString() + ", distributedFinalState="
                + report.getFinalApplicationStatus().toString() + ", appTrackingUrl=" + report.getTrackingUrl()
                + ", appUser=" + report.getUser());

        YarnApplicationState state = report.getYarnApplicationState();
        FinalApplicationStatus dsStatus = report.getFinalApplicationStatus();
        if (YarnApplicationState.FINISHED == state) {
            if (FinalApplicationStatus.SUCCEEDED == dsStatus) {
                LOG.info("Application has completed successfully. Breaking monitoring loop");
                return true;
            } else {
                LOG.info("Application did finished unsuccessfully." + " YarnState=" + state.toString()
                        + ", DSFinalStatus=" + dsStatus.toString() + ". Breaking monitoring loop");
                return false;
            }
        } else if (YarnApplicationState.KILLED == state || YarnApplicationState.FAILED == state) {
            LOG.info("Application did not finish." + " YarnState=" + state.toString() + ", DSFinalStatus="
                    + dsStatus.toString() + ". Breaking monitoring loop");
            return false;
        } else if (YarnApplicationState.RUNNING == state) {
            LOG.info("Application is running successfully. Breaking monitoring loop");
            return true;
        } else {
            if (monitorTimes-- <= 0) {
                forceKillApplication(appId);
                return false;
            }
        }
    }
}

From source file:edu.purdue.cybercenter.dm.storage.GlobusStorageFileManager.java

@Override
public void deleteFile(StorageFile storageFile) throws IOException {
    String token = storageFile.getName();

    URL task = new URL(globusBaseUrl + "/submission_id");
    HttpURLConnection connection = (HttpURLConnection) task.openConnection();
    connection.setRequestMethod("GET");
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Authorization", "Globus-Goauthtoken " + token);

    Map<String, Object> submissionIdMap = getResponse(connection);
    String submissionId = (String) submissionIdMap.get("value");

    // Preparing JSON data object
    HashMap transferFileObj = new HashMap();
    transferFileObj.put("DATA_TYPE", "delete");
    transferFileObj.put("submission_id", submissionId);
    transferFileObj.put("endpoint", globusEndpoint);
    transferFileObj.put("recursive", true);
    transferFileObj.put("label", "example delete label");

    List<HashMap> fileDeleteList = new ArrayList<HashMap>();
    HashMap delFileData = new HashMap();
    delFileData.put("path", storageFile.getLocation());//.substring(0, storageFile.getLocation().lastIndexOf('/') + 1) + storageFile.getFileName());
    delFileData.put("DATA_TYPE", "delete_item");
    fileDeleteList.add(delFileData);//from w w w .j  a  v a  2  s .c  o m

    transferFileObj.put("DATA", fileDeleteList);

    //Json data ready for transfer
    String delete = "/delete";
    task = new URL(globusBaseUrl + delete);
    connection = (HttpURLConnection) task.openConnection();
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", "Globus-Goauthtoken " + token);
    connection.setRequestProperty("Content-Type", "application/json");
    connection.setRequestProperty("Accept", "application/json");

    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.connect();
    System.out.println(Helper.deepSerialize(transferFileObj));
    BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream()));
    wr.write(Helper.deepSerialize(transferFileObj));
    wr.flush();
    wr.close();

    int responseCode = connection.getResponseCode();
    System.out.println("Response code" + responseCode);
    Map<String, Object> taskMap = getResponse(connection);//new ObjectMapper().readValue(connection.getInputStream(), HashMap.class);
    String taskId = (String) taskMap.get("task_id");//getVal(task_json,"task_id");
    connection.disconnect();

    //Section 3: Check the status of the transfer (not present in asynchronous mode)
    String getTaskStatusUrl = "/task/" + taskId;
    task = new URL(globusBaseUrl + getTaskStatusUrl);
    connection = (HttpURLConnection) task.openConnection();
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Authorization", "Globus-Goauthtoken " + token);
    connection.setRequestMethod("GET");

    String status = (String) getResponse(connection).get("status");

    while ("ACTIVE".equals(status)) {
        connection.disconnect();
        try {
            Thread.sleep(10000);
            System.out.println("Active Waiting");
        } catch (InterruptedException ex) {
            LOGGER.error("", ex);
        }
        connection = (HttpURLConnection) task.openConnection();
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization", "Globus-Goauthtoken " + token);
        connection.setRequestMethod("GET");
        status = (String) getResponse(connection).get("status");
    }
    while ("INACTIVE".equals(status)) {
        connection.disconnect();
        try {
            Thread.sleep(10000);
            System.out.println("Inactive Waiting");
        } catch (InterruptedException ex) {
            LOGGER.error("", ex);
        }
        connection = (HttpURLConnection) task.openConnection();
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Authorization", "Globus-Goauthtoken " + token);
        connection.setRequestMethod("GET");
        status = (String) getResponse(connection).get("status");
    }
    if ("SUCCEEDED".equals(status)) {
        System.out.println("SUCCEEDED");
        storageFile.remove();
    } else {
        System.out.println("Failed");
    }

}

From source file:com.tecapro.inventory.common.util.CSVReport.java

/**
 * Export CSV file/*from  w w w.  j  a v a 2  s . c o m*/
 * 
 * @param fileName
 * @param prefix
 *      Prefix file
 * @param ext
 *      Extension file
 * @param header
 *      row header
 * @param dataLines
 * @return
 *      CSV file name
 * @throws FileException 
 */
private String exportCsv(String fileName, String prefix, String ext, String[] headers, List<String[]> dataLines)
        throws FileException {
    String reportFileName = StringUtils.EMPTY;
    String reportPathDest = StringUtils.EMPTY;

    // Get report file name
    reportFileName = String.format("%s_%s%s", fileName, prefix, ext);

    // Get path work folder
    reportPathDest = propUtil.getPathProperty(FILE_PATH_WORK_PROPERTY) + File.separator;

    try {
        FileOutputStream fos = new FileOutputStream(reportPathDest + reportFileName);
        OutputStreamWriter osw = new OutputStreamWriter(fos, commonUtil.getValue(CSV_ENCODE));
        BufferedWriter bw = new BufferedWriter(osw);

        if (headers != null && headers.length > 0) {
            String header = createLineData(headers);
            bw.write(header);
            bw.write(WIN_NEW_LINE_CRLF);
        }

        Iterator<?> ite = dataLines.iterator();
        String lineData;
        while (ite.hasNext()) {
            String[] nestList = (String[]) ite.next();
            lineData = createLineData(nestList);
            bw.write(lineData);

            bw.write(WIN_NEW_LINE_CRLF);
        }
        bw.flush();
        bw.close();
    } catch (Exception e) {
        throw new FileException(e.getCause());
    }

    return reportFileName;
}

From source file:net.es.netshell.kernel.users.Users.java

private synchronized void writeUserFile() throws IOException {
    File passwordFile = new File(this.passwordFilePath.toString());
    BufferedWriter writer = new BufferedWriter(new FileWriter(passwordFile));
    for (UserProfile p : this.passwords.values()) {
        if (p.getName() != null) {
            writer.write(p.toString());//from w  ww.  j  a  v  a 2s .  c o m
            writer.newLine();
        }
    }
    writer.flush();
    writer.close();
}

From source file:br.itecbrazil.serviceftpcliente.model.ThreadEnvio.java

private boolean gravarBackup(File arquivo) {
    logger.info("Gravando backup do arquivo " + arquivo.getName() + ". Thread: "
            + Thread.currentThread().getName());

    String pathDoBackUp = arquivo.getParent().concat(File.separator).concat("backup");
    File diretorio = new File(pathDoBackUp);
    FileReader fr = null;/*w w  w . ja v a2 s . com*/
    BufferedReader br = null;
    FileWriter fw = null;
    BufferedWriter bw = null;

    try {
        if (!diretorio.exists()) {
            diretorio.mkdir();
        }

        File arquivoBackUp = new File(pathDoBackUp.concat(File.separator).concat(arquivo.getName()));

        fr = new FileReader(arquivo);
        br = new BufferedReader(fr);
        fw = new FileWriter(arquivoBackUp);
        bw = new BufferedWriter(fw);

        String linha = br.readLine();
        while (linha != null) {
            bw.write(linha);
            bw.newLine();
            bw.flush();
            coteudoFileTransfer.append(linha);
            linha = br.readLine();
        }
    } catch (FileNotFoundException ex) {
        loggerExceptionEnvio.info(ex);
        return false;
    } catch (IOException ex) {
        loggerExceptionEnvio.info(ex);
        return false;
    } finally {
        try {
            if (fr != null)
                fr.close();
            if (br != null)
                br.close();
        } catch (IOException ex) {
            loggerExceptionEnvio.info(ex);
            return false;
        }
    }

    return true;
}

From source file:org.matsim.contrib.drt.analysis.DrtRequestAnalyzer.java

public void writeAndPlotWaitTimeEstimateComparison(String plotFileName, String textFileName) {
    BufferedWriter bw = IOUtils.getBufferedWriter(textFileName);

    XYSeries times = new XYSeries("waittimes", true, true);

    try {/*from w  w w.  ja va  2s . c o m*/
        bw.append("RequestId;actualWaitTime;estimatedWaitTime;deviate");
        for (Entry<Id<Request>, Tuple<Double, Double>> e : this.waitTimeCompare.entrySet()) {
            bw.newLine();
            double first = e.getValue().getFirst();
            double second = e.getValue().getSecond();
            bw.append(e.getKey().toString() + ";" + first + ";" + second + ";" + (first - second));
            times.add(first, second);
        }
        bw.flush();
        bw.close();

        final JFreeChart chart2 = DensityScatterPlots.createPlot("Wait times", "Actual wait time [s]",
                "Initially planned wait time [s]", times, Pair.of(0., drtCfg.getMaxWaitTime()));
        //         xAxis.setLowerBound(0);
        //         yAxis.setLowerBound(0);
        ChartUtilities.writeChartAsPNG(new FileOutputStream(plotFileName), chart2, 1500, 1500);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}