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:de.tuberlin.uebb.jdae.simulation.ResultStorage.java

public Path toJson(String file) {
    Path f = Paths.get(file);
    try {/* w  w  w .j a  va  2s  .  com*/
        BufferedWriter w = Files.newBufferedWriter(f, Charset.defaultCharset());

        JsonWriter json = new JsonWriter(w);

        JsonArray jResults = new JsonArray();

        for (GlobalVariable var : dae.layout) {
            JsonObject obj = new JsonObject();
            obj.add("label", new JsonPrimitive(var.toString()));
            JsonArray data = new JsonArray();
            for (double[][] step : results) {
                JsonArray point = new JsonArray();
                point.add(new JsonPrimitive(step[0][0]));
                point.add(new JsonPrimitive(step[var.index][var.der]));
                data.add(point);
            }
            obj.add("data", data);
            jResults.add(obj);
        }

        (new Gson()).toJson(jResults, json);

        w.close();
        return f;
    } catch (IOException e) {
        // TODO Automatisch generierter Erfassungsblock
        e.printStackTrace();
    }
    return null;
}

From source file:com.ontheserverside.batch.bank.tx.SimpleElixir0Generator.java

@Override
public void generate(final File outputFile, final int numberOfTransactions) throws IOException {
    final TxGenerator txGenerator = new TxGenerator();
    final BufferedWriter writer = Files.newBufferedWriter(outputFile.toPath(), StandardCharsets.UTF_8);
    try {//from ww w  .  ja v a  2s.  c  o  m
        for (int i = 0; i < numberOfTransactions; i++) {
            writer.write(txGenerator.generate().toString());
            writer.newLine();
        }
    } finally {
        writer.close();
    }
}

From source file:ezbake.security.common.core.FileWatcherTest.java

@Test
public void testEvents() throws IOException, InterruptedException {
    final String contents = "TESTSTSETSTSTETSTSETST";

    FileWatcher w = new FileWatcher(Paths.get(folder.getRoot() + "/testFile"),
            new FileWatcher.FileWatchUpdater() {
                @Override//from   w  ww.j  a va2 s  .  c o m
                public boolean loadUpdate(InputStream is) {
                    try {
                        byte[] bytes = new byte[contents.length()];
                        is.read(bytes, 0, contents.length());
                        logger.debug("Read bytes {}", bytes);
                        Assert.assertEquals(contents, new String(bytes));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    return false;
                }

                @Override
                public void close() throws IOException {

                }
            });
    Thread watchThread = new Thread(w);
    watchThread.start();

    Thread.sleep(50);

    File f2 = folder.newFile("otherFile");
    try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(f2.toPath(), Charset.defaultCharset()))) {
        writer.println("HTESTS");
    }
    try (PrintWriter writer = new PrintWriter(Files.newBufferedWriter(f2.toPath(), Charset.defaultCharset()))) {
        writer.println("HTElkajsldkfjSTS");
    }

    File watchPath = folder.newFile("testFile");
    try (PrintWriter writer = new PrintWriter(
            Files.newBufferedWriter(watchPath.toPath(), Charset.defaultCharset()))) {
        writer.println(contents);
    }

    watchThread.join(10 * 1000);
}

From source file:org.dbpedia.spotlight.lucene.index.external.utils.SSEIndexUtils.java

public static void decodeURI(Properties config, String toDecode, String decoded) {

    LOG.info("Start to decode URIs...");

    final BufferedReader reader;
    final BufferedWriter writer;
    final Path src = Paths.get(config.getProperty("org.dbpedia.spotlight.data." + toDecode, "").trim());
    final Path dst = Paths.get(config.getProperty("org.dbpedia.spotlight.data." + decoded, "").trim());
    String line;// w  w  w.j  a v  a  2 s . c  om

    try {
        reader = Files.newBufferedReader(src, StandardCharsets.UTF_8);
        writer = Files.newBufferedWriter(dst, StandardCharsets.UTF_8);

        while ((line = reader.readLine()) != null) {
            line = line.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
            line = line.replaceAll("\\+", "%2B");
            writer.write(URLDecoder.decode(line, "UTF-8"));
            writer.newLine();
        }
        writer.close();

        LOG.info("Done");

    } catch (Exception e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
}

From source file:org.apache.lucene.benchmark.byTask.utils.StreamUtilsTest.java

private Path rawTextFile(String ext) throws Exception {
    Path f = testDir.resolve("testfile." + ext);
    BufferedWriter w = Files.newBufferedWriter(f, StandardCharsets.UTF_8);
    w.write(TEXT);/*from   w  w  w.  j a  v a  2  s  .com*/
    w.newLine();
    w.close();
    return f;
}

From source file:org.fcrepo.integration.http.api.ExternalContentPathValidatorIT.java

private static void addAllowedPath(final File allowedFile, final String allowed) throws Exception {
    try (BufferedWriter writer = Files.newBufferedWriter(allowedFile.toPath(), APPEND)) {
        writer.write(allowed + System.lineSeparator());
    }//from   w w  w.jav  a  2 s.c o m
}

From source file:eu.itesla_project.modules.simulation.ImpactAnalysisTool.java

private static void writeCsv(Multimap<String, SecurityIndex> securityIndexesPerContingency, Path outputCsvFile)
        throws IOException {
    Objects.requireNonNull(outputCsvFile);
    try (BufferedWriter writer = Files.newBufferedWriter(outputCsvFile, StandardCharsets.UTF_8)) {
        writer.write("Contingency");
        for (SecurityIndexType securityIndexType : SecurityIndexType.values()) {
            writer.write(CSV_SEPARATOR);
            writer.write(securityIndexType.toString());
        }/*  ww w.  j  a v  a2  s .c  o  m*/
        writer.newLine();

        for (Map.Entry<String, Collection<SecurityIndex>> entry : securityIndexesPerContingency.asMap()
                .entrySet()) {
            String contingencyId = entry.getKey();
            writer.write(contingencyId);
            for (String str : toRow(entry.getValue())) {
                writer.write(CSV_SEPARATOR);
                writer.write(str);
            }
            writer.newLine();
        }
    }
}

From source file:org.omegat.gui.editor.SegmentExportImport.java

private static void writeFile(File file, String content) throws IOException {
    content = content.replaceAll("\n", System.lineSeparator());
    file.delete();//from w ww .j av  a 2  s. c o  m
    try (BufferedWriter writer = Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8)) {
        writer.write(content);
    }
}

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

public void writePatientDataFile(String theIdColumn, String theDataColumn, String theOutputFile,
        File[] theDiseaseSamplesFiles) throws IOException {
    // TODO: theDiseaseSampleFile - disease in first column, rest of row is SAMPLE barcode
    TcgaGSData.printWithFlag("Metadata::writePatientDataFile - start " + theOutputFile);
    TreeMap<String, String> patientDisease = new TreeMap<>();
    try (BufferedReader br = Files.newBufferedReader(Paths.get(mMetadataFile),
            Charset.availableCharsets().get("ISO-8859-1"))) {
        // read header/write header
        int indexId = -1;
        int indexData = -1;
        {// w ww.  j  a  v  a 2 s .  com
            String line = br.readLine();
            ArrayList<String> headerArray = new ArrayList<>();
            headerArray.addAll(Arrays.asList(line.split("\t", -1)));
            indexId = headerArray.indexOf(theIdColumn);
            indexData = headerArray.indexOf(theDataColumn);
        }
        //
        for (String line = br.readLine(); null != line; line = br.readLine()) {
            String[] splitted = line.split("\t", -1);
            patientDisease.put(trimToPatientId(splitted[indexId]), splitted[indexData]);
        }
        for (File file : theDiseaseSamplesFiles) {
            TreeSet<String> barcodes = getDiseaseSampleData(file, true);
            for (String barcode : barcodes) {
                String patientId = trimToPatientId(barcode);
                if (false == patientDisease.keySet().contains(patientId)) {
                    patientDisease.put(patientId, MetadataTcgaNames.M_UNKNOWN);
                }
            }
        }
    }
    try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(theOutputFile),
            Charset.availableCharsets().get("ISO-8859-1"))) {
        bw.write("ID\tDATA");
        bw.newLine();
        for (String key : patientDisease.keySet()) {
            bw.write(key + "\t" + patientDisease.get(key));
            bw.newLine();
        }
    }
    TcgaGSData.printWithFlag("Metadata::writePatientDataFile - finished " + theOutputFile);
}

From source file:hrytsenko.gscripts.io.CsvFiles.java

/**
 * Save records into file.//from w  w w . j av a 2s .co  m
 * 
 * <p>
 * If file already exists, then it will be overridden.
 * 
 * @param records
 *            the list of records to save.
 * @param args
 *            the named arguments.
 * 
 * @throws IOException
 *             if file could not be saved.
 */
public static void saveCsv(List<Map<String, ?>> records, Map<String, ?> args) {
    if (records.isEmpty()) {
        LOGGER.info("No records to save.");
        return;
    }

    Path path = NamedArgs.findPath(args);
    LOGGER.info("Save {}.", path.getFileName());

    CsvSchema.Builder csvSchema = schemaFrom(args).setUseHeader(true);
    Records.columns(records).forEach(csvSchema::addColumn);

    try (Writer writer = Files.newBufferedWriter(path, charsetFrom(args))) {
        CsvMapper csvMapper = new CsvMapper();
        csvMapper.configure(CsvGenerator.Feature.ALWAYS_QUOTE_STRINGS, true);

        csvMapper.writer().with(csvSchema.build()).writeValue(writer, Records.normalize(records));
    } catch (IOException exception) {
        throw new AppException(String.format("Could not save file %s.", path.getFileName()), exception);
    }
}