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:eu.interedition.collatex.tools.CollationPipe.java

private static PrintWriter argumentToOutput(String arg, Charset outputCharset)
        throws ParseException, IOException {
    if ("-".equals(arg)) {
        return new PrintWriter(new OutputStreamWriter(System.out, outputCharset));
    }/*from  w  w  w  . j av a 2  s.  co m*/

    final File outFile = new File(arg);
    try {
        return new PrintWriter(Files.newBufferedWriter(outFile.toPath(), outputCharset));
    } catch (FileNotFoundException e) {
        throw new ParseException("Output file '" + outFile + "' not found");
    }
}

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

protected void writeToMD5File(String theMd5prefix, TreeMap<String, Integer> theGeneEqList,
        ArrayList<String> theGenesublist) throws IOException {
    File outputDir = getOutputDir();
    File outputFile = new File(outputDir, "matrix_data_" + theMd5prefix + ".tsv");
    TcgaGSData.printWithFlag("ProcessFile::writeToMD5File - outputFile=" + outputFile.getName());
    try (BufferedWriter bw = Files.newBufferedWriter(Paths.get(outputFile.getAbsolutePath()),
            Charset.availableCharsets().get("ISO-8859-1"))) {
        // header
        for (String sample : mSampleList) {
            bw.write("\t");
            bw.write(sample);/*w ww. jav  a  2s .c om*/
        }
        bw.newLine();
        boolean foundNAN = false;
        for (String geneEq : theGenesublist) {
            // gene eq
            //TcgaGSData.printWithFlag(y + "="+mGeneEqList.get(y));
            bw.write(geneEq);
            // data
            int y = theGeneEqList.get(geneEq).intValue();
            for (int x = 0; x < mSampleList.size(); x++) {
                bw.write("\t");
                String dVal = "NaN";
                if (Double.NaN != mCombinedData[x][y]) {
                    dVal = Double.toString(mCombinedData[x][y]);
                    if ("NaN".equalsIgnoreCase(dVal)) {
                        //TcgaGSData.printWithFlag("NaN <-- " + mCombinedData[x][y]);
                        foundNAN = true;
                    }
                }
                bw.write(dVal);
            }
            bw.newLine();
        }
        if (true == foundNAN) {
            TcgaGSData.printWithFlag("Found NaN writing " + outputFile.getAbsolutePath());
        }
    }
}

From source file:edu.vt.vbi.patric.cache.DataLandingGenerator.java

public boolean createCacheFileProteinFamilies(String filePath) {
    boolean isSuccess = false;
    JSONObject jsonData = new JSONObject();
    JSONObject data;//from  w w  w  .j a  v a  2  s .co  m

    // from WP
    // data
    data = read(baseURL + "/tab/dlp-proteinfamilies-data/?req=passphrase");
    if (data != null) {
        jsonData.put("data", data);
    }
    // tools
    data = read(baseURL + "/tab/dlp-proteinfamilies-tools/?req=passphrase");
    if (data != null) {
        jsonData.put("tools", data);
    }
    // process
    data = read(baseURL + "/tab/dlp-proteinfamilies-process/?req=passphrase");
    if (data != null) {
        jsonData.put("process", data);
    }
    // download
    data = read(baseURL + "/tab/dlp-proteinfamilies-download/?req=passphrase");
    if (data != null) {
        jsonData.put("download", data);
    }
    //
    // add popularGenra
    data = getPopularGeneraFigfam();
    if (data != null) {
        jsonData.put("popularGenomes", data);
    }
    // add figfam graph data
    data = getProteinFamilies();
    if (data != null) {
        jsonData.put("FIGfams", data);
    }

    // save jsonData to file
    try (PrintWriter jsonOut = new PrintWriter(
            Files.newBufferedWriter(FileSystems.getDefault().getPath(filePath), Charset.defaultCharset()));) {
        jsonData.writeJSONString(jsonOut);
        isSuccess = true;
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
    }
    return isSuccess;
}

From source file:org.apache.lucene.benchmark.byTask.feeds.LineDocSourceTest.java

public void testInvalidFormat() throws Exception {
    String[] testCases = new String[] { "", // empty line
            "title", // just title
            "title" + WriteLineDocTask.SEP, // title + SEP
            "title" + WriteLineDocTask.SEP + "body", // title + SEP + body
            // note that title + SEP + body + SEP is a valid line, which results in an
            // empty body
    };/* w w w. ja  va 2s .c  o  m*/

    for (int i = 0; i < testCases.length; i++) {
        Path file = getWorkDir().resolve("one-line");
        BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8);
        writer.write(testCases[i]);
        writer.newLine();
        writer.close();
        expectThrows(Exception.class, () -> {
            doIndexAndSearchTest(file, null, null);
        });
    }
}

From source file:co.cask.cdap.internal.app.services.http.handlers.WorkflowHttpHandlerTest.java

private String createInput(String folderName) throws IOException {
    File inputDir = tmpFolder.newFolder(folderName);

    File inputFile = new File(inputDir.getPath() + "/words.txt");
    try (BufferedWriter writer = Files.newBufferedWriter(inputFile.toPath(), Charsets.UTF_8)) {
        writer.write("this text has");
        writer.newLine();/*from   w  w w .  j a  v  a  2  s .co m*/
        writer.write("two words text inside");
    }
    return inputDir.getAbsolutePath();
}

From source file:eu.itesla_project.eurostag.EurostagImpactAnalysis.java

private static void dumpLinesDictionary(Network network, EurostagDictionary dictionary, Path dir)
        throws IOException {
    try (BufferedWriter os = Files.newBufferedWriter(dir.resolve("dict_lines.csv"), StandardCharsets.UTF_8)) {
        for (Identifiable obj : Identifiables.sort(Iterables.concat(network.getLines(),
                network.getTwoWindingsTransformers(), network.getDanglingLines()))) {
            os.write(obj.getId() + ";" + dictionary.getEsgId(obj.getId()));
            os.newLine();/* ww w.  j a  v  a2 s. c o m*/
        }
        for (ThreeWindingsTransformer twt : Identifiables.sort(network.getThreeWindingsTransformers())) {
            throw new AssertionError("TODO");
        }
    }
}

From source file:org.nuxeo.github.Analyzer.java

/**
 * @return true if there are unsigned contributors
 *//*from w ww  .  java2 s . com*/
protected boolean saveAndPrint() {
    Set<Developer> allContributors = new TreeSet<>();
    allContributors.addAll(developersByLogin.values());
    allContributors.addAll(developersByName.values());
    log.info(String.format("Found %s contributors", allContributors.size()));
    if (output == null) {
        output = Paths.get(System.getProperty("java.io.tmpdir"), "contributors.csv");
    }
    boolean unsigned = false;
    Path tmpFile;
    try {
        tmpFile = Files.createTempFile("contributors", ".csv");
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return false;
    }
    try (CSVWriter writer = new CSVWriter(Files.newBufferedWriter(tmpFile, Charset.defaultCharset()), '\t')) {
        writer.writeNext(CSV_HEADER);
        for (Developer dev : allContributors) {
            if (!unsigned && dev.getAliases().isEmpty() && !"Nuxeo".equalsIgnoreCase(dev.getCompany())
                    && !dev.isSigned()) {
                unsigned = true;
            }
            log.debug(dev);
            writer.writeNext(new String[] { dev.getLogin(), dev.getName(), Boolean.toString(dev.isSigned()),
                    setToString(dev.getEmails()), dev.getCompany(), dev.getUrl(), setToString(dev.getAliases()),
                    dev.isSigned() || "Nuxeo".equalsIgnoreCase(dev.getCompany())
                            || "ex-Nuxeo".equalsIgnoreCase(dev.getCompany()) ? ""
                                    : commitsToString(dev.getCommits()) });
        }
        Files.copy(tmpFile, output, StandardCopyOption.REPLACE_EXISTING);
        Files.delete(tmpFile);
        log.info("Saved to file: " + output);
    } catch (IOException e) {
        log.error("See " + tmpFile + System.lineSeparator() + e.getMessage(), e);
    }
    return unsigned;
}

From source file:org.sonar.scanner.report.ReportPublisher.java

private void dumpMetadata(Map<String, String> metadata) {
    Path file = projectReactor.getRoot().getWorkDir().toPath().resolve(METADATA_DUMP_FILENAME);
    try (Writer output = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
        for (Map.Entry<String, String> entry : metadata.entrySet()) {
            output.write(entry.getKey());
            output.write("=");
            output.write(entry.getValue());
            output.write("\n");
        }// w w w.ja  v a  2 s.c  o  m

        LOG.debug("Report metadata written to {}", file);
    } catch (IOException e) {
        throw new IllegalStateException("Unable to dump " + file, e);
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.DatasetFactory.java

/**
 * Verify/download/update artifact in cache. Execute post-download actions.
 *///from   www . j a  v a  2s . c o  m
private void materialize(DatasetDescription aDataset) throws IOException {
    Path root = resolve(aDataset);
    Collection<ArtifactDescription> artifacts = aDataset.getArtifacts().values();

    // First validate if local copies are still up-to-date
    boolean reload = false;
    packageValidationLoop: for (ArtifactDescription artifact : artifacts) {
        Path cachedFile = resolve(aDataset, artifact);
        if (!Files.exists(cachedFile)) {
            continue;
        }

        if (artifact.getSha1() != null) {
            String actual = getDigest(cachedFile, "SHA1");
            if (!artifact.getSha1().equals(actual)) {
                LOG.info("Local SHA1 hash mismatch on [" + cachedFile + "] - expected [" + artifact.getSha1()
                        + "] - actual [" + actual + "]");
                reload = true;
                break packageValidationLoop;
            } else {
                LOG.info("Local SHA1 hash verified on [" + cachedFile + "] - [" + actual + "]");
            }
        }
    }

    // If any of the packages are outdated, clear the cache and download again
    if (reload) {
        LOG.info("Clearing local cache for [" + root + "]");
        FileUtils.deleteQuietly(root.toFile());
    }

    for (ArtifactDescription artifact : artifacts) {
        Path cachedFile = resolve(aDataset, artifact);

        if (Files.exists(cachedFile)) {
            continue;
        }

        if (artifact.getText() != null) {
            Files.createDirectories(cachedFile.getParent());

            LOG.info("Creating [" + cachedFile + "]");
            try (Writer out = Files.newBufferedWriter(cachedFile, StandardCharsets.UTF_8)) {
                out.write(artifact.getText());
            }
        }

        if (artifact.getUrl() != null) {
            Files.createDirectories(cachedFile.getParent());

            MessageDigest sha1;
            try {
                sha1 = MessageDigest.getInstance("SHA1");
            } catch (NoSuchAlgorithmException e) {
                throw new IOException(e);
            }

            URL source = new URL(artifact.getUrl());

            LOG.info("Fetching [" + cachedFile + "]");

            URLConnection connection = source.openConnection();
            connection.setRequestProperty("User-Agent", "Java");

            try (InputStream is = connection.getInputStream()) {
                DigestInputStream sha1Filter = new DigestInputStream(is, sha1);
                Files.copy(sha1Filter, cachedFile);

                if (artifact.getSha1() != null) {
                    String sha1Hex = new String(Hex.encodeHex(sha1Filter.getMessageDigest().digest()));
                    if (!artifact.getSha1().equals(sha1Hex)) {
                        String message = "SHA1 mismatch. Expected [" + artifact.getSha1() + "] but got ["
                                + sha1Hex + "].";
                        LOG.error(message);
                        throw new IOException(message);
                    }
                }
            }
        }
    }

    // Perform a post-fetch action such as unpacking
    Path postActionCompleteMarker = resolve(aDataset).resolve(".postComplete");
    if (!Files.exists(postActionCompleteMarker)) {
        for (ArtifactDescription artifact : artifacts) {
            Path cachedFile = resolve(aDataset, artifact);

            List<ActionDescription> actions = artifact.getActions();
            if (actions != null && !actions.isEmpty()) {
                try {
                    for (ActionDescription action : actions) {
                        LOG.info("Post-download action [" + action.getAction() + "]");
                        Class<? extends Action_ImplBase> implClass = actionRegistry.get(action.getAction());

                        if (implClass == null) {
                            throw new IllegalStateException(
                                    "Unknown or unsupported action [" + action.getAction() + "]");
                        }

                        Action_ImplBase impl = implClass.newInstance();
                        impl.apply(action, aDataset, artifact, cachedFile);
                    }
                } catch (IllegalStateException e) {
                    throw e;
                } catch (IOException e) {
                    throw e;
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            }
        }
        Files.createFile(postActionCompleteMarker);
    }
}

From source file:com.mapr.synth.SchemaSamplerTest.java

@Test
public void testFileSampler() throws IOException {
    File f = new File("numbers.tsv");
    f.deleteOnExit();//from   w w  w .  ja v  a2s  .c om

    BufferedWriter out = Files.newBufferedWriter(f.toPath(), Charsets.UTF_8);
    out.write("a\tb\n");
    for (int i = 0; i < 20; i++) {
        out.write(i + "\t" + (i * i) + "\n");
    }
    out.close();

    SchemaSampler s = new SchemaSampler(
            Resources.asCharSource(Resources.getResource("schema008.json"), Charsets.UTF_8).read());

    for (int k = 0; k < 1000; k++) {
        JsonNode r = s.sample();
        assertEquals(6, r.get("x").get("x").asInt() + r.get("x").get("y").asInt());
        int i = r.get("y").get("a").asInt();
        assertEquals(i * i, r.get("y").get("b").asInt());
    }
}