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.duracloud.snapshot.service.impl.SpaceItemWriterTest.java

private BufferedWriter createWriter(File contentDir, String name) throws IOException {
    Path propsPath = ContentDirUtils.getPath(contentDir, name);
    BufferedWriter propsWriter = Files.newBufferedWriter(propsPath, StandardCharsets.UTF_8);
    return propsWriter;
}

From source file:popgenutils.dfcp.PrepareVCF4DFCP.java

/**
 * /* w  ww .  ja  va 2  s  . c o  m*/
 */
private void makegeno() {
    gt_string_builder = new StringBuilder();
    StringBuilder header = new StringBuilder();
    try (BufferedReader in = Files.newBufferedReader(Paths.get(filename), Charset.forName("UTF-8"))) {
        BufferedWriter out = null;
        BufferedWriter out_bgl_ref = null;
        BufferedWriter out_bgl_geno = null;

        String line = null;
        int number_of_individuals = 0;
        Set<Integer> individuals_to_genotype = new HashSet<Integer>();
        while ((line = in.readLine()) != null) {

            if (line.startsWith("#CHROM")) {
                StringBuilder bglref_header = new StringBuilder();
                StringBuilder bglgeno_header = new StringBuilder();
                String[] parts = line.split("\t");
                //samples begin at 9
                number_of_individuals = parts.length - 9;
                List<Integer> index_of_individuals = new ArrayList<Integer>();
                for (int i = 0; i < number_of_individuals; i++) {
                    index_of_individuals.add(i);
                }
                Collections.shuffle(index_of_individuals);
                if (pgeno >= 0) {
                    // convert pgeno into ageno
                    ageno = (int) Math.ceil(number_of_individuals * pgeno);
                }
                for (int i = 0; i < ageno; i++) {
                    individuals_to_genotype.add(index_of_individuals.get(i));
                }

                bglref_header.append(parts[0]);
                bglgeno_header.append(parts[0]);
                for (int i = 1; i < 9; i++) {
                    bglref_header.append("\t" + parts[i]);
                    bglgeno_header.append("\t" + parts[i]);
                }
                for (int i = 9; i < parts.length; i++) {
                    int index = i - 9;
                    if (individuals_to_genotype.contains(index)) {
                        bglgeno_header.append("\t" + parts[i]);
                    } else {
                        bglref_header.append("\t" + parts[i]);
                    }
                }
                out = Files.newBufferedWriter(
                        Paths.get(output_dir + "/" + ageno + "_geno" + Paths.get(filename).getFileName()),
                        Charset.forName("UTF-8"));
                out_bgl_ref = Files.newBufferedWriter(
                        Paths.get(
                                output_dir + "/" + ageno + "_geno_bglref" + Paths.get(filename).getFileName()),
                        Charset.forName("UTF-8"));
                out_bgl_geno = Files.newBufferedWriter(
                        Paths.get(output_dir + "/" + ageno + "_geno_bgl" + Paths.get(filename).getFileName()),
                        Charset.forName("UTF-8"));
                out.write(header.toString());
                out_bgl_ref.write(header.toString());
                out_bgl_geno.write(header.toString());
                out.write(line + System.getProperty("line.separator"));
                out_bgl_geno.write(bglgeno_header + System.getProperty("line.separator"));
                out_bgl_ref.write(bglref_header + 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;
                }
                out.write(parts[0]);
                out_bgl_geno.write(parts[0]);
                out_bgl_ref.write(parts[0]);
                for (int i = 1; i < parts.length; i++) {
                    if (i > 8) {
                        parts2 = parts[i].split(":");
                        if (gt_pos == 0 && individuals_to_genotype.contains(i - 9)) {
                            out.write("\t" + convertToGT(parts2[0]));
                            out_bgl_geno.write("\t" + convertToGT(parts2[0]));
                        } else {
                            out.write("\t" + parts2[0]);
                            out_bgl_ref.write("\t" + parts2[0]);
                        }
                        for (int j = 1; j < parts2.length; j++) {
                            if (gt_pos == j && individuals_to_genotype.contains(i - 9)) {
                                out.write(":" + convertToGT(parts2[i]));
                                out_bgl_geno.write(":" + convertToGT(parts2[i]));
                            } else {
                                out.write(":" + parts2[i]);
                                out_bgl_ref.write(":" + parts2[i]);
                            }
                        }
                    } else {
                        out.write("\t" + parts[i]);
                        out_bgl_ref.write("\t" + parts[i]);
                        out_bgl_geno.write("\t" + parts[i]);
                    }
                }
                out.write(System.getProperty("line.separator"));
                out_bgl_ref.write(System.getProperty("line.separator"));
                out_bgl_geno.write(System.getProperty("line.separator"));
            }
        }
        out.close();
        out_bgl_ref.close();
        out_bgl_geno.close();
    } catch (IOException e) {
        System.err.println("could not read from file " + filename);
        e.printStackTrace();
    }
}

From source file:sadl.models.PDTTAold.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 boolean abnormal = getFinalTransition(state).isAbnormal();
        final double finalProb = getFinalStateProbability(state);
        if (finalProb > 0 || (compressed && finalProb > 0.01)) {
            writer.write("double");
        }/*from   w w w .j a  v  a  2s.  co m*/
        writer.write("circle");
        if (abnormal) {
            writer.write(", color=red");
        }
        if (finalProb > 0 || (compressed && finalProb > 0.01)) {
            writer.write(", label=\"");
            writer.write(Integer.toString(state));
            writer.write("&#92;np= ");
            writer.write(Double.toString(Precision.round(finalProb, 2)));
            writer.write("\"");
        }
        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(t.getSymbol());
        if (t.getProbability() > 0) {
            writer.write(" p=");
            writer.write(Double.toString(Precision.round(t.getProbability(), 2)));
        }
        if (t.isAbnormal()) {
            writer.write("<BR/>");
            writer.write("<FONT COLOR=\"red\">");
            writer.write(Integer.toString(t.getAnomalyInsertionType().getTypeIndex()));
            writer.write("</FONT>");
        }
        writer.write(">");
        if (t.isAbnormal()) {
            writer.write(" color=\"red\"");
        }
        writer.write(";];\n");

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

}

From source file:sadl.models.PDFA.java

public void toGraphvizFile(Path graphvizResult, boolean compressed, Map<String, String> idReplacement)
        throws IOException {
    try (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 boolean abnormal = getFinalTransition(state).isAbnormal();
            final double finalProb = getFinalStateProbability(state);
            if (finalProb > 0 || (compressed && finalProb > 0.01)) {
                writer.write("double");
            }//from   w  w w .j  a  v a  2  s . co  m
            writer.write("circle");
            if (abnormal) {
                writer.write(", color=red");
            }
            if (finalProb > 0 || (compressed && finalProb > 0.01)) {
                writer.write(", label=\"");
                writer.write(Integer.toString(state));
                writer.write("&#92;np= ");
                writer.write(Double.toString(Precision.round(finalProb, 2)));
                writer.write("\"");
            }
            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=<");
            if (idReplacement != null && idReplacement.containsKey(t.getSymbol())) {
                writer.write(idReplacement.get(t.getSymbol()));
            } else {
                writer.write(t.getSymbol());
            }
            if (t.getProbability() > 0) {
                writer.write(" p=");
                writer.write(Double.toString(Precision.round(t.getProbability(), 2)));
            }
            if (t.isAbnormal()) {
                writer.write("<BR/>");
                writer.write("<FONT COLOR=\"red\">");
                writer.write(Integer.toString(t.getAnomalyInsertionType().getTypeIndex()));
                writer.write("</FONT>");
            }
            writer.write(">");
            if (t.isAbnormal()) {
                writer.write(" color=\"red\"");
            }
            writer.write(";];\n");

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

}

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

public boolean createCacheFileAntibioticResistanceGenes(String filePath) {
    boolean isSuccess = false;
    JSONObject jsonData = new JSONObject();
    JSONObject data;/*from   w w w.  j a  va  2 s . com*/

    // from WP
    // data
    data = read(baseURL + "/tab/dlp-antibioticresistance-data/?req=passphrase");
    if (data != null) {
        jsonData.put("data", data);
    }
    // popular genomes
    data = this.getPopularGenomesForAntibioticResistanceGene();
    if (data != null) {
        jsonData.put("popularGenomes", data);
    }
    // tools
    data = read(baseURL + "/tab/dlp-antibioticresistance-tools/?req=passphrase");
    if (data != null) {
        jsonData.put("tools", data);
    }
    // process
    data = read(baseURL + "/tab/dlp-antibioticresistance-process/?req=passphrase");
    if (data != null) {
        jsonData.put("process", data);
    }
    // download
    data = read(baseURL + "/tab/dlp-antibioticresistance-download/?req=passphrase");
    if (data != null) {
        jsonData.put("download", 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:io.seqware.pipeline.plugins.FileProvenanceQueryTool.java

private Path populateOriginalReportFromWS() throws IOException {
    Map<FileProvenanceParam, List<String>> map = ProvenanceUtility.convertOptionsToMap(options, metadata);
    // specify some standard filters that are required for filters
    map.put(FileProvenanceParam.skip, new ImmutableList.Builder<String>().add("false").build());
    map.put(FileProvenanceParam.workflow_run_status,
            new ImmutableList.Builder<String>().add(WorkflowRunStatus.completed.toString()).build());
    map.put(FileProvenanceParam.processing_status,
            new ImmutableList.Builder<String>().add(ProcessingStatus.success.toString()).build());
    Path originalReport = Files.createTempFile("file_provenance", "txt");
    Log.debug("Original report written to " + originalReport.toString());
    try (BufferedWriter originalWriter = Files.newBufferedWriter(originalReport, Charset.defaultCharset())) {
        metadata.fileProvenanceReport(map, originalWriter);
    }/*from w  w w.  j a  v a 2 s .c o  m*/
    return originalReport;
}

From source file:org.apache.cassandra.db.VerifyTest.java

protected void writeChecksum(long checksum, String filePath) {
    File outFile = new File(filePath);
    BufferedWriter out = null;/*w w  w  .ja va 2 s.c om*/
    try {
        out = Files.newBufferedWriter(outFile.toPath(), Charsets.UTF_8);
        out.write(String.valueOf(checksum));
        out.flush();
        out.close();
    } catch (IOException e) {
        throw new FSWriteError(e, outFile);
    } finally {
        FileUtils.closeQuietly(out);
    }

}

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

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

    // from WP
    // data
    data = read(baseURL + "/tab/dlp-transcriptomics-data/?req=passphrase");
    if (data != null) {
        jsonData.put("data", data);
    }
    // tools
    data = read(baseURL + "/tab/dlp-transcriptomics-tools/?req=passphrase");
    if (data != null) {
        jsonData.put("tools", data);
    }
    // process
    data = read(baseURL + "/tab/dlp-transcriptomics-process/?req=passphrase");
    if (data != null) {
        jsonData.put("process", data);
    }
    // download
    data = read(baseURL + "/tab/dlp-transcriptomics-download/?req=passphrase");
    if (data != null) {
        jsonData.put("download", data);
    }
    // topSpecies
    data = getTopSpeciesForTranscriptomics();
    if (data != null) {
        jsonData.put("topSpecies", data);
    }
    // featuredExperiment
    data = getFeaturedExperimentForTranscriptomics();
    if (data != null) {
        jsonData.put("featuredExperiment", data);
    }
    // popularGenomes
    data = getPopularGenomesForTranscriptomics();
    if (data != null) {
        jsonData.put("popularGenomes", 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:de.upb.timok.run.GenericSmacPipeline.java

private void splitTrainTestFile(String timedInputFile, String timedInputTrainFile, String timedInputTestFile,
        double trainPercentage, double testPercentage, double anomalyPercentage, boolean isRti)
        throws IOException {
    logger.info("TimedInputFile=" + timedInputFile);
    final File f = new File(timedInputFile);
    System.out.println(f);//ww w. j av a  2 s.c om
    final LineNumberReader lnr = new LineNumberReader(new FileReader(timedInputFile));
    lnr.skip(Long.MAX_VALUE);
    int samples = lnr.getLineNumber();
    lnr.close();
    final int trainingSamples = (int) (samples * trainPercentage);
    final int testSamples = (int) (samples * testPercentage);
    final int anomalies = (int) (anomalyPercentage * testSamples);
    final int writtenTrainingSamples = 0;
    final int writtenTestSamples = 0;
    int insertedAnomalies = 0;
    final BufferedReader br = Files.newBufferedReader(Paths.get(timedInputFile), StandardCharsets.UTF_8);
    String line = null;
    final BufferedWriter trainWriter = Files.newBufferedWriter(Paths.get(timedInputTrainFile),
            StandardCharsets.UTF_8);
    final BufferedWriter testWriter = Files.newBufferedWriter(Paths.get(timedInputTestFile),
            StandardCharsets.UTF_8);
    final Random r = new Random(MasterSeed.nextLong());
    final Random mutation = new Random(MasterSeed.nextLong());
    boolean force = false;
    int lineIndex = 0;
    int linesLeft;
    int anomaliesToInsert;
    if (isRti) {
        br.readLine();
        samples--;
    }
    while ((line = br.readLine()) != null) {
        if (writtenTrainingSamples < trainingSamples && writtenTestSamples < testSamples) {
            // choose randomly according to train/test percentage
            if (r.nextDouble() > testPercentage) {
                // write to train
                writeSample(new TimedSequence(line, true, false).toTrebaString(), trainWriter);
            } else {
                // write to test
                insertedAnomalies = testAndWriteAnomaly(anomalies, insertedAnomalies, anomalyPercentage, line,
                        testWriter, mutation, force);
            }
        } else if (writtenTrainingSamples >= trainingSamples) {
            insertedAnomalies = testAndWriteAnomaly(anomalies, insertedAnomalies, anomalyPercentage, line,
                    testWriter, mutation, force);
        } else if (writtenTestSamples >= testSamples) {
            // only write trainSamples from now on
            writeSample(new TimedSequence(line, true, false).toTrebaString(), trainWriter);
        }
        lineIndex++;
        linesLeft = samples - lineIndex;
        anomaliesToInsert = anomalies - insertedAnomalies;
        if (linesLeft <= anomaliesToInsert) {
            force = true;
        }
    }
    br.close();
    trainWriter.close();
    testWriter.close();
}

From source file:br.bireme.ngrams.NGrams.java

/**
 *
 * @param index//ww w .j av a 2 s .c  o  m
 * @param schema
 * @param inFile
 * @param inFileEncoding
 * @param outFile
 * @param outFileEncoding
 * @throws IOException
 * @throws ParseException
 */
public static void search(final NGIndex index, final NGSchema schema, final String inFile,
        final String inFileEncoding, final String outFile, final String outFileEncoding)
        throws IOException, ParseException {
    if (index == null) {
        throw new NullPointerException("index");
    }
    if (schema == null) {
        throw new NullPointerException("schema");
    }
    if (inFile == null) {
        throw new NullPointerException("inFile");
    }
    if (inFileEncoding == null) {
        throw new NullPointerException("inFileEncoding");
    }
    if (outFile == null) {
        throw new NullPointerException("outFile");
    }
    if (outFileEncoding == null) {
        throw new NullPointerException("outFileEncoding");
    }
    final Charset inCharset = Charset.forName(inFileEncoding);
    final Charset outCharset = Charset.forName(outFileEncoding);
    final IndexSearcher searcher = index.getIndexSearcher();
    final NGAnalyzer analyzer = (NGAnalyzer) index.getAnalyzer();
    final Parameters parameters = schema.getParameters();
    final NGramDistance ngDistance = new NGramDistance(analyzer.getNgramSize());
    final Set<String> id_id = new HashSet<>();
    int cur = 0;
    try (final BufferedReader reader = Files.newBufferedReader(new File(inFile).toPath(), inCharset);
            final BufferedWriter writer = Files.newBufferedWriter(new File(outFile).toPath(), outCharset)) {
        writer.append("rank|similarity|search_doc_id|index_doc_id|"
                + "ngram_search_text|ngram_index_text|search_source|" + "index_source\n");

        final Set<Result> results = new HashSet<>();
        while (true) {
            final String line = reader.readLine();
            if (line == null) {
                break;
            }
            if (++cur % 250 == 0) {
                System.out.println("<<< " + cur);
            }

            results.clear();
            final String tline = line.replace(':', ' ').trim();
            if (!tline.isEmpty()) {
                final String[] split = tline.split(" *\\| *", Integer.MAX_VALUE);
                if (split.length != parameters.nameFields.size()) {
                    throw new IOException("invalid number of fields: " + line);
                }
                searchRaw(parameters, searcher, analyzer, ngDistance, tline, true, id_id, results);
                if (!results.isEmpty()) {
                    writeOutput(parameters, results, writer);
                }
            }
        }
        searcher.getIndexReader().close();
    }
}