Example usage for java.nio.file Files newBufferedWriter

List of usage examples for java.nio.file Files newBufferedWriter

Introduction

In this page you can find the example usage for java.nio.file Files newBufferedWriter.

Prototype

public static BufferedWriter newBufferedWriter(Path path, OpenOption... options) throws IOException 

Source Link

Document

Opens or creates a file for writing, returning a BufferedWriter to write text to the file in an efficient manner.

Usage

From source file:org.zaproxy.zap.utils.TableExportAction.java

@Override
public void actionPerformed(ActionEvent e) {
    WritableFileChooser chooser = new WritableFileChooser(
            Model.getSingleton().getOptionsParam().getUserDirectory()) {

        private static final long serialVersionUID = 1L;

        @Override//  w  w w. j  av  a 2  s.  c o  m
        public void approveSelection() {
            File file = getSelectedFile();
            if (file != null) {
                String filePath = file.getAbsolutePath();
                if (!filePath.toLowerCase(Locale.ROOT).endsWith(CSV_EXTENSION)) {
                    setSelectedFile(new File(filePath + CSV_EXTENSION));
                }
            }

            super.approveSelection();
        }
    };

    chooser.setSelectedFile(new File(Constant.messages.getString("export.button.default.filename")));
    if (chooser.showSaveDialog(View.getSingleton().getMainFrame()) == WritableFileChooser.APPROVE_OPTION) {
        boolean success = true;
        try (CSVPrinter pw = new CSVPrinter(
                Files.newBufferedWriter(chooser.getSelectedFile().toPath(), StandardCharsets.UTF_8),
                CSVFormat.DEFAULT)) {
            pw.printRecord(getColumnNames());
            int rowCount = getTable().getRowCount();
            for (int row = 0; row < rowCount; row++) {
                pw.printRecord(getRowCells(row));
            }
        } catch (Exception ex) {
            success = false;
            JOptionPane.showMessageDialog(View.getSingleton().getMainFrame(),
                    Constant.messages.getString("export.button.error") + "\n" + ex.getMessage());
            LOGGER.error("Export Failed: " + ex.getMessage(), ex);
        }

        // Delay the presentation of success message, to ensure all the data was already flushed.
        if (success) {
            JOptionPane.showMessageDialog(View.getSingleton().getMainFrame(),
                    Constant.messages.getString("export.button.success"));
        }
    }
}

From source file:org.mda.bcb.tcgagsdata.create.ReadPlatform.java

protected void writeFile() throws IOException {
    TcgaGSData.printWithFlag("writeFile " + mWriteFile);
    try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(mWriteFile),
            Charset.availableCharsets().get("ISO-8859-1"))) {
        // write header of samples
        for (String sample : mSamples) {
            bw.write("\t" + sample);
        }//  w w  w  .ja  v a  2 s. c  om
        bw.newLine();
        // write rows
        for (int index = 0; index < mNumberOfGenes; index++) {
            // write gene
            bw.write(mGenes[index]);
            // write data
            for (double data : mGenesBySamplesValues[index]) {
                bw.write("\t" + data);
            }
            bw.newLine();
        }
    }
    TcgaGSData.printWithFlag("writeFile finished");
}

From source file:eu.itesla_project.modules.wca.WCATool.java

private static void writeClustersCsv(Map<String, Map<String, WCACluster>> clusterPerContingencyPerBaseCase,
        Set<String> contingencyIds, Path outputCsvFile) throws IOException {
    try (BufferedWriter writer = Files.newBufferedWriter(outputCsvFile, StandardCharsets.UTF_8)) {
        writer.write("base case");
        for (String contingencyId : contingencyIds) {
            writer.write(CSV_SEPARATOR);
            writer.write("cluster num " + contingencyId);
        }/*  ww  w  . j  av  a  2 s . c o  m*/
        for (String contingencyId : contingencyIds) {
            writer.write(CSV_SEPARATOR);
            writer.write("cluster cause " + contingencyId);
        }
        writer.newLine();
        for (Map.Entry<String, Map<String, WCACluster>> entry : clusterPerContingencyPerBaseCase.entrySet()) {
            String baseCaseName = entry.getKey();
            Map<String, WCACluster> clusterNumPerContingency = entry.getValue();
            writer.write(baseCaseName);
            for (String contingencyId : contingencyIds) {
                WCACluster cluster = clusterNumPerContingency.get(contingencyId);
                writer.write(CSV_SEPARATOR);
                if (cluster != null) {
                    writer.write(cluster.getNum().toIntValue() + " (" + cluster.getOrigin() + ")");
                } else {
                    writer.write("");
                }
            }
            for (String contingencyId : contingencyIds) {
                WCACluster cluster = clusterNumPerContingency.get(contingencyId);
                writer.write(CSV_SEPARATOR);
                if (cluster != null) {
                    writer.write(cluster.getCauses().stream().collect(Collectors.joining("|")));
                } else {
                    writer.write("");
                }
            }
            writer.newLine();
        }
    }
}

From source file:sadl.detectors.AnomalyDetector.java

public boolean[] areAnomalies(TimedInput testSequences) {
    if (Settings.isDebug()) {
        final Path testLabelFile = Paths.get("testLabels.csv");
        try {/*  w w w.j ava 2 s . c o  m*/
            Files.deleteIfExists(testLabelFile);
            Files.createFile(testLabelFile);
        } catch (final IOException e1) {
            logger.error("Unexpected exception occured", e1);
        }
        try (BufferedWriter bw = Files.newBufferedWriter(testLabelFile, StandardCharsets.UTF_8)) {
            for (final TimedWord s : testSequences) {
                bw.append(s.getLabel().toString());
                bw.append('\n');
            }
        } catch (final IOException e) {
            logger.error("Unexpected exception occured", e);
        }
    }
    final boolean[] result = new boolean[testSequences.size()];

    // parallelism does not destroy determinism
    final IntConsumer f = (i -> {
        final TimedWord s = testSequences.get(i);
        result[i] = isAnomaly(s);
    });
    if (Settings.isParallel()) {
        IntStream.range(0, testSequences.size()).parallel().forEach(f);
    } else {
        IntStream.range(0, testSequences.size()).forEach(f);
    }
    return result;
}

From source file:net.sourceforge.pmd.renderers.YAHTMLRenderer.java

private void renderClasses(String outputDir) throws IOException {
    for (ReportNode node : reportNodesByPackage.values()) {
        if (node.hasViolations()) {
            try (PrintWriter out = new PrintWriter(Files.newBufferedWriter(
                    new File(outputDir, node.getClassName() + ".html").toPath(), StandardCharsets.UTF_8))) {
                out.println("<!DOCTYPE html>");
                out.println("<html>");
                out.println("    <head>");
                out.println("        <meta charset=\"UTF-8\">");
                out.print("        <title>PMD - ");
                out.print(node.getClassName());
                out.println("</title>");
                out.println("    </head>");
                out.println("    <body>");
                out.println("        <h2>Class View</h2>");
                out.print("        <h3 align=\"center\">Class: ");
                out.print(node.getClassName());
                out.println("</h3>");
                out.println("        <table border=\"\" align=\"center\" cellspacing=\"0\" cellpadding=\"3\">");
                out.println("        <tr><th>Method</th><th>Violation</th></tr>");
                for (RuleViolation violation : node.getViolations()) {
                    out.print("        <tr><td>");
                    out.print(violation.getMethodName());
                    out.print("</td><td>");
                    out.print("<table border=\"0\">");

                    out.print(renderViolationRow("Rule:", violation.getRule().getName()));
                    out.print(renderViolationRow("Description:", violation.getDescription()));

                    if (StringUtils.isNotBlank(violation.getVariableName())) {
                        out.print(renderViolationRow("Variable:", violation.getVariableName()));
                    }//w  w w .java  2  s .c  o  m

                    out.print(renderViolationRow("Line:",
                            violation.getEndLine() > 0
                                    ? violation.getBeginLine() + " and " + violation.getEndLine()
                                    : String.valueOf(violation.getBeginLine())));

                    out.print("</table>");

                    out.print("</td></tr>");
                    out.println();
                }
                out.println("        </table>");
                out.println("    </body>");
                out.println("</html>");
            }
        }
    }
}

From source file:de.dev.eth0.elasticsearch.aem.indexing.ElasticSearchIndexContentBuilder.java

private ReplicationContent createReplicationContent(ReplicationContentFactory factory, IndexEntry content)
        throws ReplicationException {
    Path tempFile;//from  w  w w. jav a 2 s.com

    try {
        tempFile = Files.createTempFile("elastic_index", ".tmp");
    } catch (IOException e) {
        throw new ReplicationException("Could not create temporary file", e);
    }

    try (BufferedWriter writer = Files.newBufferedWriter(tempFile, Charset.forName("UTF-8"))) {
        ObjectMapper mapper = new ObjectMapper();
        writer.write(mapper.writeValueAsString(content));
        writer.flush();

        return factory.create("text/plain", tempFile.toFile(), true);
    } catch (IOException e) {
        throw new ReplicationException("Could not write to temporary file", e);
    }
}

From source file:org.apache.asterix.extension.grammar.GrammarExtensionMojo.java

private void generateOutput() throws MojoExecutionException {
    File outputFile = prepareOutputFile();
    try (BufferedWriter writer = Files.newBufferedWriter(outputFile.toPath(), StandardCharsets.UTF_8)) {
        // Options
        if (optionsBlock != null) {
            writer.write(OPTIONS);/* www  .  j  a  v a  2 s  .c  o  m*/
            writer.write(optionsBlock);
        }
        writer.newLine();

        // Parser Begin
        writer.write(PARSER_BEGIN);
        writer.write(OPEN_PAREN);
        writer.write(parserClassName);
        writer.write(CLOSE_PAREN);
        writer.newLine();
        writer.newLine();

        // Package
        writer.write(KWPACKAGE);
        writer.write(" ");
        writer.write(packageName);
        writer.write(SEMICOLON);
        writer.newLine();
        writer.newLine();

        // Imports
        List<String> importList = new ArrayList<>();
        for (List<String> importTokens : imports) {
            importList.add(importToString(importTokens));
        }
        Collections.sort(importList);
        for (String importStatement : importList) {
            writer.write(importStatement);
            writer.newLine();
        }

        writer.newLine();

        // Class definition
        writer.write(baseClassDef.replaceAll(baseClassName, parserClassName));
        writer.newLine();

        // Parser End
        writer.write(PARSER_END);
        writer.write(OPEN_PAREN);
        writer.write(parserClassName);
        writer.write(CLOSE_PAREN);
        writer.newLine();
        writer.newLine();

        // Extinsibles
        for (Entry<String, Pair<String, String>> entry : extensibles.entrySet()) {
            writer.newLine();
            String signature = entry.getKey();
            if (mergeElements.containsKey(signature)) {
                writer.write("// Merged Non-terminal");
                writer.newLine();
            }
            writer.write(extensibleSignatureToOutput(signature));
            writer.newLine();
            if (mergeElements.containsKey(signature)) {
                merge(writer, entry.getValue(), mergeElements.get(signature));
            } else {
                writer.write(entry.getValue().first);
                writer.newLine();
                if (entry.getValue().second != null) {
                    writer.write(entry.getValue().second);
                    writer.newLine();
                }
            }
        }

        for (Pair<String, String> element : extensionFinals) {
            writer.write(toOutput(element.first));
            writer.newLine();
            writer.write(element.second);
            writer.newLine();
        }

        for (Pair<String, String> element : baseFinals) {
            writer.write(toOutput(element.first));
            writer.newLine();
            writer.write(element.second);
            writer.newLine();
        }

    } catch (Exception e) {
        getLog().error(e);
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:org.mda.bcb.tcgagsdata.create.ProcessFile.java

protected void writeMapFile(GeneNames_Mixin theGnm) throws IOException {
    File mapFile = new File(mDataDir, theGnm.mDataName.toLowerCase() + "map.tsv");
    try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(mapFile.getAbsolutePath()),
            Charset.availableCharsets().get("ISO-8859-1"))) {
        bw.write("probe_id\tchromosome\tprobe_location\tgene_id");
        bw.newLine();/*from  w  ww  .  j av  a  2  s . co  m*/
        for (String probe : theGnm.mProbeToGeneSymbolMap.keySet()) {
            bw.write(probe);
            bw.write("\t");
            bw.write(theGnm.mProbeToChromosomeMap.get(probe));
            bw.write("\t");
            bw.write(theGnm.mProbeToGenomicLocationMap.get(probe));
            bw.write("\t");
            bw.write(theGnm.mProbeToGeneSymbolMap.get(probe));
            bw.write("\t");
            bw.newLine();
        }
    }

}

From source file:org.apache.tika.eval.tools.TopCommonTokenCounter.java

private static void writeTopN(Path path, AbstractTokenTFDFPriorityQueue queue) throws IOException {
    if (Files.isRegularFile(path)) {
        System.err.println("File " + path.getFileName() + " already exists. Skipping.");
        return;// w  w w  . j  a  va 2 s. c o m
    }
    Files.createDirectories(path.getParent());
    BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8);
    StringBuilder sb = new StringBuilder();
    //add these tokens no matter what
    for (String t : WHITE_LIST) {
        writer.write(t);
        writer.newLine();
    }
    for (TokenDFTF tp : queue.getArray()) {
        writer.write(getRow(sb, tp) + "\n");

    }
    writer.flush();
    writer.close();
}