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.apache.druid.query.aggregation.datasketches.tuple.GenerateTestData.java

private static void generateBucketTestData() throws Exception {
    double meanTest = 10;
    double meanControl = 10.2;
    Path path = FileSystems.getDefault().getPath("bucket_test_data.tsv");
    try (BufferedWriter out = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
        Random rand = ThreadLocalRandom.current();
        for (int i = 0; i < 1000; i++) {
            writeBucketTestRecord(out, "test", i, rand.nextGaussian() + meanTest);
            writeBucketTestRecord(out, "control", i, rand.nextGaussian() + meanControl);
        }//from   w  w  w  .  ja  v a 2  s  .  com
    }
}

From source file:org.tallison.wikilinks.ExternalLinkExtractor.java

private void execute(Path gzLinksFile, Path table) throws IOException {
    BufferedWriter writer = Files.newBufferedWriter(table, StandardCharsets.UTF_8);
    int recordCount = 0;
    try (InputStream is = new BufferedInputStream(
            new GZIPInputStream(Files.newInputStream(gzLinksFile), 10000000))) {
        readToVALUES(is);/*from   www.ja v  a2s. com*/
        boolean keepGoing = true;
        while (keepGoing) {
            int chr = is.read();

            switch (chr) {
            case OPEN_PAREN:
                readRecord(is, writer);
                recordCount++;
                if (recordCount % 1000 == 0) {
                    System.out.println(recordCount);
                }
                break;
            case -1:
                keepGoing = false;
                break;
            }
        }
    } finally {
        writer.flush();
        writer.close();
    }
}

From source file:eu.itesla_project.modules.rules.CheckSecurityTool.java

private static void writeCsv(
        Map<String, Map<SecurityIndexType, SecurityRuleCheckStatus>> checkStatusPerContingency,
        Set<SecurityIndexType> securityIndexTypes, Path outputCsvFile) throws IOException {
    Objects.requireNonNull(outputCsvFile);

    try (BufferedWriter writer = Files.newBufferedWriter(outputCsvFile, StandardCharsets.UTF_8)) {
        writer.write("Contingency");
        for (SecurityIndexType securityIndexType : securityIndexTypes) {
            writer.write(CSV_SEPARATOR);
            writer.write(securityIndexType.toString());
        }/* ww  w.  j a va2  s  .c o  m*/
        writer.newLine();

        for (Map.Entry<String, Map<SecurityIndexType, SecurityRuleCheckStatus>> entry : checkStatusPerContingency
                .entrySet()) {
            String contingencyId = entry.getKey();
            Map<SecurityIndexType, SecurityRuleCheckStatus> checkStatus = entry.getValue();

            writer.write(contingencyId);

            for (SecurityIndexType securityIndexType : securityIndexTypes) {
                writer.write(CSV_SEPARATOR);
                writer.write(checkStatus.get(securityIndexType).name());
            }

            writer.newLine();
        }
    }
}

From source file:cz.muni.fi.editor.typemanager.TypeServiceImpl.java

@Override
public void save(String filename, Type type) throws IllegalArgumentException {
    Path target = fileSystemProvider.getFileSystem().getPath("/", filename);

    try {/*w ww  .j a  va  2  s.c om*/
        createBackup(target);
        try (BufferedWriter bw = Files.newBufferedWriter(target, Charset.forName("UTF-8"))) {
            marshaller.marshal(type, bw);
        }
    } catch (IOException | JAXBException ex) {
        throw new IllegalArgumentException(ex);
    }
}

From source file:eu.itesla_project.modules.offline.ExportSecurityIndexesTool.java

@Override
public void run(CommandLine line) throws Exception {
    String simulationDbName = line.hasOption("simulation-db-name") ? line.getOptionValue("simulation-db-name")
            : OfflineConfig.DEFAULT_SIMULATION_DB_NAME;
    OfflineConfig config = OfflineConfig.load();
    OfflineDb offlineDb = config.getOfflineDbFactoryClass().newInstance().create(simulationDbName);
    String workflowId = line.getOptionValue("workflow");
    Path outputFile = Paths.get(line.getOptionValue("output-file"));
    char delimiter = ';';
    if (line.hasOption("delimiter")) {
        String value = line.getOptionValue("delimiter");
        if (value.length() != 1) {
            throw new RuntimeException("A character is expected");
        }/*from  w  w  w  .  j a va  2  s.  c  o  m*/
        delimiter = value.charAt(0);
    }
    OfflineAttributesFilter stateAttrFilter = OfflineAttributesFilter.ALL;
    if (line.hasOption("attributes-filter")) {
        stateAttrFilter = OfflineAttributesFilter.valueOf(line.getOptionValue("attributes-filter"));
    }
    boolean addSampleColumn = line.hasOption("add-sample-column");
    boolean keepAllSamples = line.hasOption("keep-all-samples");
    try (Writer writer = Files.newBufferedWriter(outputFile, StandardCharsets.UTF_8)) {
        offlineDb.exportCsv(workflowId, writer,
                new OfflineDbCsvExportConfig(delimiter, stateAttrFilter, addSampleColumn, keepAllSamples));
    }
}

From source file:io.github.robwin.diff.DiffAssert.java

private static void writeHtmlReport(Path reportPath, LinkedList<DiffMatchPatch.Diff> diffs) {
    DiffMatchPatch differ = new DiffMatchPatch();
    try {//from  w w w .  j  av a  2 s  . c om
        Files.createDirectories(reportPath.getParent());
        try (BufferedWriter writer = Files.newBufferedWriter(reportPath, Charset.forName("UTF-8"))) {
            writer.write(differ.diff_prettyHtml(diffs));
        }
    } catch (IOException e) {
        throw new RuntimeException(String.format("Failed to write report %s", reportPath.toAbsolutePath()), e);
    }
}

From source file:com.bancvue.mongomigrate.CreateCommand.java

public int execute() {
    int exitCode = 0;
    Path file = null;/*w w  w .  j  a v  a 2s. c om*/
    try {
        // Ensure migrations folder exists.
        Path folder = Paths.get(migrationsFolder);
        if (!Files.exists(folder)) {
            Files.createDirectories(folder);
        }

        // Generate filename and ensure it doesn't already exist.
        file = Paths.get(migrationsFolder, generateMigrationFileName(migrationName));
        if (Files.exists(file))
            throw new FileAlreadyExistsException(file.toAbsolutePath().toString());

        // Write the file.
        BufferedWriter writer = Files.newBufferedWriter(file, Charset.forName("UTF-8"));
        writer.write("// Add migration javascript here.\n");
        writer.write("db.<collection_name>.update(\n");
        writer.write("    { <query> },\n");
        writer.write("    { <update> },\n");
        writer.write("    { multi: true }\n");
        writer.write(");\n");
        writer.flush();
        writer.close();

        System.out.println("Created migration file: " + file.toString());

    } catch (FileAlreadyExistsException e) {
        System.err.println("The specified migration file " + file.toString() + " already exists.");
        exitCode = 1;
    } catch (IOException e) {
        e.printStackTrace();
        exitCode = 1;
    }
    return exitCode;
}

From source file:org.ulyssis.ipp.publisher.FileOutput.java

@Override
public void outputScore(Score score) {
    Path tmpFile = null;//  www.ja va 2s.  co m
    try {
        if (tmpDir.isPresent()) {
            tmpFile = Files.createTempFile(tmpDir.get(), "score-", ".json",
                    PosixFilePermissions.asFileAttribute(defaultPerms));
        } else {
            tmpFile = Files.createTempFile("score-", ".json",
                    PosixFilePermissions.asFileAttribute(defaultPerms));
        }
        BufferedWriter writer = Files.newBufferedWriter(tmpFile, StandardCharsets.UTF_8);
        Serialization.getJsonMapper().writer(new DefaultPrettyPrinter()).writeValue(writer, score);
        Files.move(tmpFile, filePath, StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        LOG.error("Error writing score to file!", e);
    } finally {
        try {
            if (tmpFile != null)
                Files.deleteIfExists(tmpFile);
        } catch (IOException ignored) {
        }
    }
}

From source file:springfox.documentation.staticdocs.SwaggerResultHandler.java

/**
 * Apply the action on the given result.
 *
 * @param result the result of the executed request
 * @throws Exception if a failure occurs
 *//*from w  w  w. j  a  v  a2 s  .c om*/
@Override
public void handle(MvcResult result) throws Exception {
    MockHttpServletResponse response = result.getResponse();
    String swaggerJson = response.getContentAsString();
    Files.createDirectories(Paths.get(outputDir));
    try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputDir, fileName),
            StandardCharsets.UTF_8)) {
        writer.write(swaggerJson);
    }
}

From source file:org.lucidj.gluon.GluonUtil.java

public static void dumpRepresentation(GluonInstance root, String filename) {
    // TODO: THIS SHOULD BE RECONFIGURABLE
    Path userdir = get_data_dir();

    if (userdir == null) {
        return;/*from  w w w .j  a v a2s  . c  om*/
    }

    Path destination_path = userdir.resolve(filename);
    Charset cs = Charset.forName("UTF-8");
    Writer writer = null;

    try {
        writer = Files.newBufferedWriter(destination_path, cs);
        dump_instance(root, writer, 1);
    } catch (Exception e) {
        log.error("Exception on serialization", e);
    } finally {
        try {
            if (writer != null) {
                writer.close();
            }
        } catch (Exception ignore) {
        }
        ;
    }
}