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:edu.mit.fss.examples.member.gui.PowerSubsystemPanel.java

/**
 * Export this panel's generation dataset.
 *///from  w  ww .  ja  va  2  s. c  o  m
private void exportDataset() {
    if (JFileChooser.APPROVE_OPTION == fileChooser.showSaveDialog(this)) {
        File f = fileChooser.getSelectedFile();

        if (!f.exists() || JOptionPane.YES_OPTION == JOptionPane.showConfirmDialog(this,
                "Overwrite existing file " + f.getName() + "?", "File Exists", JOptionPane.YES_NO_OPTION)) {

            logger.info("Exporting dataset to file " + f.getPath() + ".");
            try {
                BufferedWriter bw = Files.newBufferedWriter(Paths.get(f.getPath()), Charset.defaultCharset());

                StringBuilder b = new StringBuilder();
                b.append(" Generation\n").append("Time, Value\n");
                for (int j = 0; j < generationSeries.getItemCount(); j++) {
                    b.append(generationSeries.getTimePeriod(j).getStart().getTime()).append(", ")
                            .append(generationSeries.getValue(j)).append("\n");
                }

                bw.write(b.toString());
                bw.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
    }
}

From source file:com.gs.obevo.db.impl.platforms.oracle.OracleReveng.java

@Override
protected File printInstructions(PrintStream out, AquaRevengArgs args) {
    DbEnvironment env = getDbEnvironment(args);

    JdbcDataSourceFactory jdbcFactory = new OracleJdbcDataSourceFactory();
    DataSource ds = jdbcFactory.createDataSource(env, new Credential(args.getUsername(), args.getPassword()),
            1);//from  w ww .ja  va 2  s.  c  o m
    JdbcHelper jdbc = new JdbcHelper(null, false);

    Path interim = new File(args.getOutputPath(), "interim").toPath();
    interim.toFile().mkdirs();
    try (Connection conn = ds.getConnection();
            BufferedWriter fileWriter = Files.newBufferedWriter(interim.resolve("output.sql"),
                    Charset.defaultCharset())) {
        // https://docs.oracle.com/database/121/ARPLS/d_metada.htm#BGBJBFGE
        // Note - can't remap schema name, object name, tablespace name within JDBC calls; we will leave that to the existing code in AbstractDdlReveng
        jdbc.update(conn,
                "{ CALL DBMS_METADATA.SET_TRANSFORM_PARAM(DBMS_METADATA.SESSION_TRANSFORM,'STORAGE',false) }");

        MutableList<Map<String, Object>> maps = jdbc.queryForList(conn,
                "SELECT CASE WHEN OBJECT_TYPE = 'TABLE' THEN 1 WHEN OBJECT_TYPE = 'INDEX' THEN 2 ELSE 3 END SORT_ORDER,\n"
                        + "    OBJECT_TYPE,\n"
                        + "    dbms_metadata.get_ddl(REPLACE(object_type,' ','_'), object_name, owner) || ';' AS object_ddl\n"
                        + "FROM DBA_OBJECTS WHERE OWNER = '" + args.getDbSchema()
                        + "' AND OBJECT_TYPE NOT IN ('PACKAGE BODY', 'LOB','MATERIALIZED VIEW', 'TABLE PARTITION')\n"
                        + "ORDER BY 1");

        for (Map<String, Object> map : maps) {
            Clob clobObject = (Clob) map.get("OBJECT_DDL");
            InputStream in = clobObject.getAsciiStream();
            StringWriter w = new StringWriter();
            try {
                IOUtils.copy(in, w);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            String clobAsString = w.toString();
            clobAsString = clobAsString.replaceAll(";.*$", "");

            LOG.debug("Content for {}: ", map.get("OBJECT_TYPE"), clobAsString);
            fileWriter.write(clobAsString);
            fileWriter.newLine();
            fileWriter.write("~");
            fileWriter.newLine();
        }
    } catch (SQLException | IOException e) {
        throw new RuntimeException(e);
    }

    return interim.toFile();
}

From source file:sonicScream.services.SettingsService.java

/**
 *Serializes all current settings objects out to disk, to the specified directory, 
 * relative to the current directory. A folder separator is automatically 
 * appended to the passed string.//from w ww  . ja  v a2s.com
 * @param pathToWriteTo The name, or relative path of the folder to write to, without a trailing slash.
 */
public void saveSettings(String pathToWriteTo) {
    if (pathToWriteTo.length() > 2
            && !(pathToWriteTo.charAt(pathToWriteTo.length() - 1) == File.separatorChar)) {
        pathToWriteTo = pathToWriteTo.concat(File.separator);
    }
    try {
        JAXBContext context = JAXBContext.newInstance(SettingsMapWrapper.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        Path settingsFile = Paths.get(pathToWriteTo, Constants.SETTINGS_FILE_NAME);
        try (BufferedWriter bw = Files.newBufferedWriter(settingsFile, StandardOpenOption.CREATE)) {
            SettingsMapWrapper wrapper = new SettingsMapWrapper();
            wrapper.setSettingsMap(_settingsDictionary);
            m.marshal(wrapper, bw);
        } catch (IOException ex) {
            System.err.println("Failed to write out " + Constants.SETTINGS_FILE_NAME);
        }

        context = JAXBContext.newInstance(CRCsMapWrapper.class);
        m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        Path crcFile = Paths.get(pathToWriteTo, Constants.CRC_CACHE_FILE_NAME);
        try (BufferedWriter bw = Files.newBufferedWriter(crcFile, StandardOpenOption.CREATE)) {
            CRCsMapWrapper wrapper = new CRCsMapWrapper();
            wrapper.setCRCsMap(_crcDictionary);
            m.marshal(wrapper, bw);
        } catch (IOException ex) {
            System.err.println("Failed to write out " + Constants.CRC_CACHE_FILE_NAME);
        }

        context = JAXBContext.newInstance(Profile.class);
        m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        for (Profile profile : _profileList) {
            try {
                Files.createDirectories(Paths.get(pathToWriteTo, Constants.PROFILES_DIRECTORY, File.separator,
                        profile.getProfileName()));
            } catch (IOException ex) {
                //TODO: Tell the user
                ex.printStackTrace();
                break;
            }
            Path profilePath = Paths.get(pathToWriteTo, Constants.PROFILES_DIRECTORY, File.separator,
                    profile.getProfileName(), File.separator,
                    profile.getProfileName() + "_" + Constants.PROFILE_FILE_SUFFIX);
            try (BufferedWriter bw = Files.newBufferedWriter(profilePath)) {
                m.marshal(profile, bw);
            } catch (IOException ex) {
                System.err.printf("\nFailed to write out profile: %s " + ex.getMessage());
            }
        }
    } catch (JAXBException ex) {
        //TODO: Error message
        ex.printStackTrace();
    }

}

From source file:org.sleuthkit.autopsy.timeline.snapshot.SnapShotReportWriter.java

/**
 * Fill in the mustache template at the given location using the values from
 * the given context object and save it to the given outPutFile.
 *
 * @param templateLocation The location of the template. suitible for use
 *                         with Class.getResourceAsStream
 * @param templateName     The name of the tempalte. (Used by mustache to
 *                         cache templates?)
 * @param context          The contect to use to fill in the template
 *                         values.//from  w w w .  j a  v a  2  s. c om
 * @param outPutFile       The filled in tempalte will be saced at this
 *                         Path.
 *
 * @throws IOException If there is a problem saving the filled in template
 *                     to disk.
 */
private void fillTemplateAndWrite(final String templateLocation, final String templateName, Object context,
        final Path outPutFile) throws IOException {

    Mustache summaryMustache = mf.compile(
            new InputStreamReader(SnapShotReportWriter.class.getResourceAsStream(templateLocation)),
            templateName);
    try (Writer writer = Files.newBufferedWriter(outPutFile, Charset.forName("UTF-8"))) { //NON-NLS
        summaryMustache.execute(writer, context);
    }
}

From source file:eu.itesla_project.modules.validation.OfflineValidationTool.java

private static void writeAttributesFiles(Set<RuleId> rulesIds,
        Map<String, Map<RuleId, Map<HistoDbAttributeId, Object>>> valuesPerRulePerCase, Path outputDir)
        throws IOException {
    for (RuleId ruleId : rulesIds) {
        Path attributesFile = outputDir.resolve("attributes_" + ruleId.toString() + ".csv");

        System.out.println("writing " + attributesFile + "...");

        try (BufferedWriter writer = Files.newBufferedWriter(attributesFile, StandardCharsets.UTF_8)) {
            writer.write("base case");

            Set<HistoDbAttributeId> allAttributeIds = new LinkedHashSet<>();
            for (Map<RuleId, Map<HistoDbAttributeId, Object>> valuesPerRule : valuesPerRulePerCase.values()) {
                Map<HistoDbAttributeId, Object> values = valuesPerRule.get(ruleId);
                if (values != null) {
                    allAttributeIds.addAll(values.keySet());
                }//from  w ww . j a v a 2  s.  co  m
            }

            for (HistoDbAttributeId attributeId : allAttributeIds) {
                writer.write(CSV_SEPARATOR);
                writer.write(attributeId.toString());
            }
            writer.newLine();

            for (Map.Entry<String, Map<RuleId, Map<HistoDbAttributeId, Object>>> e : valuesPerRulePerCase
                    .entrySet()) {
                String baseCaseName = e.getKey();
                Map<RuleId, Map<HistoDbAttributeId, Object>> valuesPerRule = e.getValue();
                writer.write(baseCaseName);

                Map<HistoDbAttributeId, Object> values = valuesPerRule.get(ruleId);
                for (HistoDbAttributeId attributeId : allAttributeIds) {
                    writer.write(CSV_SEPARATOR);
                    Object value = values.get(attributeId);
                    if (value != null && !(value instanceof Float && Float.isNaN((Float) value))) {
                        writer.write(Objects.toString(values.get(attributeId)));
                    }
                }

                writer.newLine();
            }
        }
    }
}

From source file:sadl.models.pdta.PDTA.java

public void toGraphvizFile(Path resultPath) throws IOException {
    try (BufferedWriter writer = Files.newBufferedWriter(resultPath, StandardCharsets.UTF_8)) {
        writer.write("digraph G {\n");

        // write states
        for (final PDTAState state : states.valueCollection()) {

            writer.write(Integer.toString(state.getId()));
            writer.write(" [shape=");

            if (state.isFinalState()) {
                writer.write("double");
            }/*from   w w  w .  j  a  v  a 2 s  .  c o m*/

            writer.write("circle, label=\"" + Integer.toString(state.getId()) + "\"");
            writer.write("]\n");
        }

        for (final PDTAState state : states.valueCollection()) {
            for (final TreeMap<Double, PDTATransition> transitions : state.getTransitions().values()) {
                for (final PDTATransition transition : transitions.values()) {
                    writer.write(Integer.toString(state.getId()) + "->"
                            + Integer.toString(transition.getTarget().getId()) + " [label=<"
                            + transition.getEvent().getSymbol() + ">;];\n");
                }
            }
        }

        writer.write("}");
    }
}

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

protected void writeDiseaseToSampleFile() throws IOException {
    File outputDir = getOutputDir();
    File outputFile = new File(outputDir, "disease_sample.tsv");
    try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(outputFile.getAbsolutePath()),
            Charset.availableCharsets().get("ISO-8859-1"))) {
        for (ArrayList<String> outputList : mDiseaseToSampleLists) {
            boolean first = true;
            for (String data : outputList) {
                if (false == first) {
                    bw.write("\t");
                } else {
                    first = false;//  ww  w . j ava  2 s . c  om
                }
                bw.write(data);
            }
            bw.newLine();
        }
    }
}

From source file:tmn.dev.project.Player.java

/**
 * Generate an HTML file containing the player's data in order to display
 * this information in a web browser/* w  w w  .j a  va2s.  c  o m*/
 * 
 * @param fileToWrite
 *            The .html file where the player data will be written
 * @throws IOException
 */
public void writeToHTML(File fileToWrite) throws IOException {
    // Compute the values we will need
    computeTotalsAndAvg();

    // Create the batting average over time plot
    String baPlotName = createBAPlot();

    // Initialize the file writer
    BufferedWriter writer = Files.newBufferedWriter(fileToWrite.toPath(), Charset.forName("UTF-8"));

    // Write the HTML file header
    writeHeader(writer);

    // Write the player data to HTML
    writeStatBoxes(writer);

    // Write the batting average plot
    writeBAPlot(writer, baPlotName);

    // Write the NTML file footer
    writeFooter(writer);

    // Close the file
    writer.close();
}

From source file:de.upb.timok.models.PDTTA.java

public void toGraphvizFile(Path graphvizResult, boolean compressed) throws IOException {
    final BufferedWriter writer = Files.newBufferedWriter(graphvizResult, StandardCharsets.UTF_8);
    writer.write("digraph G {\n");
    // start states
    writer.write("qi [shape = point ];");
    // write states
    for (final int state : finalStateProbabilities.keys()) {
        writer.write(Integer.toString(state));
        writer.write(" [shape=");
        final double finalProb = finalStateProbabilities.get(state);
        if (finalProb > 0 || (compressed && finalProb > 0.01)) {
            writer.write("double");
        }/*from   w  w  w  . j  ava  2  s .  c om*/
        writer.write("circle, label=\"");
        writer.write(Integer.toString(state));
        if (finalProb > 0 || (compressed && finalProb > 0.01)) {
            writer.write(" - P= ");
            writer.write(Double.toString(Precision.round(finalProb, 2)));
        }
        writer.write("\"];\n");
    }
    writer.write("qi -> 0;");
    // write transitions
    for (final Transition t : transitions) {
        if (compressed && t.getProbability() <= 0.01) {
            continue;
        }
        // 0 -> 0 [label=0.06];
        writer.write(Integer.toString(t.getFromState()));
        writer.write(" -> ");
        writer.write(Integer.toString(t.getToState()));
        writer.write(" [label=\"");
        writer.write(Integer.toString(t.getSymbol()));
        if (t.getProbability() > 0) {
            writer.write(" p=");
            writer.write(Double.toString(Precision.round(t.getProbability(), 2)));
        }
        writer.write("\"];\n");

    }
    writer.write("}");
    writer.close();

}

From source file:popgenutils.dfcp.PrepareVCF4DFCP.java

/**
 * /*from  ww w . j  a v  a  2s.  c  o m*/
 */
private void filterhet() {
    StringBuilder header = new StringBuilder();
    try (BufferedReader in = Files.newBufferedReader(Paths.get(filename), Charset.forName("UTF-8"))) {
        BufferedWriter out = null;

        String line = null;
        while ((line = in.readLine()) != null) {

            if (line.startsWith("#CHROM")) {
                //samples begin at 9
                out = Files.newBufferedWriter(
                        Paths.get(
                                output_dir + "/" + hetindex + "_hetfilter" + Paths.get(filename).getFileName()),
                        Charset.forName("UTF-8"));
                out.write(header.toString());
                out.write(line + System.getProperty("line.separator"));
            } else if (line.startsWith("#")) {
                header.append(line + System.getProperty("line.separator"));
            } else {
                // format at 8
                String[] parts = line.split("\t");
                String[] parts2 = parts[8].split(":");
                int gt_pos = 0;
                for (int i = 1; i < parts2.length; i++) {
                    if (parts2[i].equals("GT"))
                        gt_pos = i;
                }
                parts2 = parts[9 + hetindex].split("\\||/");
                if (!parts2[0].equals(parts2[1]))
                    out.write(line + System.getProperty("line.separator"));
            }
        }
        out.close();
    } catch (IOException e) {
        System.err.println("could not read from file " + filename);
        e.printStackTrace();
    }
}