Example usage for java.io BufferedWriter BufferedWriter

List of usage examples for java.io BufferedWriter BufferedWriter

Introduction

In this page you can find the example usage for java.io BufferedWriter BufferedWriter.

Prototype

public BufferedWriter(Writer out) 

Source Link

Document

Creates a buffered character-output stream that uses a default-sized output buffer.

Usage

From source file:com.orange.mmp.bind.JSONClientBinding.java

/**
 *    Sends the request to WebService and return an object built from
 *    JSON response./*from   w w w  .  j  a v a 2 s  .  c  om*/
 *    @return A binding object in a JSONObject, JSONArray or String
 */
public Object getResponse(InputStream postData) throws BindingException {
    StringWriter responseContent = new StringWriter();
    BufferedReader reader = null;
    BufferedWriter writer = null;
    //Get response
    try {
        this.getHttpConnection().init(this.buildURL(), this.timeout);
        if (postData != null)
            this.getHttpConnection().sendData(postData);
        InputStream httpIn = this.getHttpConnection().getData();
        if (httpIn != null) {
            writer = new BufferedWriter(responseContent);
            reader = new BufferedReader(new InputStreamReader(httpIn, Constants.DEFAULT_ENCODING));
            String line = null;
            while ((line = reader.readLine()) != null) {
                writer.write(line);
                writer.newLine();
                writer.flush();
            }
        } else
            return null;

    } catch (UnsupportedEncodingException uee) {
        throw new BindingException("Unsupported encoding from " + this.epr + " : " + uee.getMessage());
    } catch (IOException ioe) {
        throw new BindingException("Failed to get response : " + ioe.getMessage());
    } catch (MMPNetException mne) {
        throw new BindingException("Failed to get response : " + mne.getMessage());
    } finally {
        try {
            if (reader != null)
                reader.close();
            if (writer != null)
                writer.close();
            this.releaseConnection();
        } catch (MMPNetException mne) {
            //Nop, logs in AOP
        } catch (IOException ioe) {
            //Nop, logs in AOP
        }
    }

    //Parse response
    if (responseContent == null)
        throw new BindingException("Failed to parse response : empty result");
    String jsonString = responseContent.toString();
    if (jsonString.length() == 0)
        throw new BindingException("Failed to parse response : empty result");
    try {
        JSONTokener tokener = new JSONTokener(jsonString);
        return tokener.nextValue();
    } catch (JSONException je) {
        throw new BindingException("Failed to parse response : " + je.getMessage());
    }
}

From source file:fr.sanofi.fcl4transmart.controllers.listeners.snpData.SetTissueListener.java

@Override
public void handleEvent(Event event) {
    Vector<String> values = this.ui.getValues();
    Vector<String> samples = this.ui.getSamples();
    File file = new File(this.dataType.getPath().toString() + File.separator
            + this.dataType.getStudy().toString() + ".subject_mapping.tmp");
    File mappingFile = ((SnpData) this.dataType).getMappingFile();
    if (mappingFile == null) {
        this.ui.displayMessage("Error: no subject to sample mapping file");
    }//w w w.  j a  v  a 2  s. c om
    try {
        FileWriter fw = new FileWriter(file);
        BufferedWriter out = new BufferedWriter(fw);

        try {
            BufferedReader br = new BufferedReader(new FileReader(mappingFile));
            String line;
            while ((line = br.readLine()) != null) {
                String[] fields = line.split("\t", -1);
                String sample = fields[3];
                String tissueType;
                if (samples.contains(sample)) {
                    tissueType = values.get(samples.indexOf(sample));
                } else {
                    br.close();
                    return;
                }
                out.write(fields[0] + "\t" + fields[1] + "\t" + fields[2] + "\t" + sample + "\t" + fields[4]
                        + "\t" + tissueType + "\t" + fields[6] + "\t" + fields[7] + "\t" + "PLATFORM+TISSUETYPE"
                        + "\n");
            }
            br.close();
        } catch (Exception e) {
            this.ui.displayMessage("File error: " + e.getLocalizedMessage());
            out.close();
            e.printStackTrace();
        }
        out.close();
        try {
            File fileDest;
            if (mappingFile != null) {
                String fileName = mappingFile.getName();
                mappingFile.delete();
                fileDest = new File(this.dataType.getPath() + File.separator + fileName);
            } else {
                fileDest = new File(this.dataType.getPath() + File.separator
                        + this.dataType.getStudy().toString() + ".subject_mapping");
            }
            FileUtils.moveFile(file, fileDest);
            ((SnpData) this.dataType).setMappingFile(fileDest);
        } catch (IOException ioe) {
            this.ui.displayMessage("File error: " + ioe.getLocalizedMessage());
            return;
        }
    } catch (Exception e) {
        this.ui.displayMessage("Error: " + e.getLocalizedMessage());
        e.printStackTrace();
    }
    this.ui.displayMessage("Subject to sample mapping file updated");
    WorkPart.updateSteps();
    WorkPart.updateFiles();
}

From source file:edu.harvard.iq.dvn.ingest.dsb.impl.DvnJavaFieldCutter.java

public void subsetFile(InputStream in, String outfile, Set<Integer> columns, Long numCases, String delimiter) {
    try {/*from  ww  w  .j  ava2  s .  co  m*/
        Scanner scanner = new Scanner(in);

        dbgLog.fine("outfile=" + outfile);

        BufferedWriter out = new BufferedWriter(new FileWriter(outfile));
        scanner.useDelimiter("\\n");

        for (long caseIndex = 0; caseIndex < numCases; caseIndex++) {
            if (scanner.hasNext()) {
                String[] line = (scanner.next()).split(delimiter, -1);
                List<String> ln = new ArrayList<String>();
                for (Integer i : columns) {
                    ln.add(line[i]);
                }
                out.write(StringUtils.join(ln, "\t") + "\n");
            } else {
                throw new RuntimeException("Tab file has fewer rows than the determined number of cases.");
            }
        }

        while (scanner.hasNext()) {
            if (!"".equals(scanner.next())) {
                throw new RuntimeException(
                        "Tab file has extra nonempty rows than the determined number of cases.");

            }
        }

        scanner.close();
        out.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:eu.h2020.symbiote.model.Registry.java

public void registerMapping(BigInteger mappingId, BigInteger modelId1, BigInteger modelId2, String mapping)
        throws UnsupportedEncodingException {
    // use library to parse mapping file to RDF, then read RDFXML into store
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try (PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out, "UTF-8")), true)) {
        AlignmentParser parser = new AlignmentParser(0);
        parser.initAlignment(null);//from  w  w  w.j a va2 s . co  m
        try {
            parser.parseString(mapping).render(new RDFRendererVisitor(writer));
        } catch (AlignmentException e) {
            log.error("Couldn't load the alignment:", e);
        }
        writer.flush();
    }
    String mappingRDF = out.toString();
    Model model = ModelFactory.createDefaultModel();
    model.read(new ByteArrayInputStream(out.toByteArray()), null, RDFFormat.RDFXML.toString());

    tripleStore.insertGraph(Ontology.getMappingGraphURI(mappingId), model, RDFFormat.RDFXML);
    tripleStore.insertGraph(Ontology.MAPPING_GRAPH, Ontology.getMappingMetadata(modelId1, modelId2, mappingId),
            RDFFormat.NTriples);
    log.debug(String.format("mapping registered: modelId1={}, modelId2={}, mapping={}", modelId1, modelId2,
            mappingRDF));
}

From source file:edu.cmu.cs.lti.ark.fn.data.prep.ParsePreparation.java

/**
 * Converts a POS tagged file into conll format
 * @param posFile/*  ww w .  j  a  v  a2  s  . c om*/
 * @param conllInputFile
 */
public static void printCoNLLTypeInput(String posFile, String conllInputFile) throws IOException {
    List<String> posSentences = readLines(posFile);
    BufferedWriter bWriter = new BufferedWriter(new FileWriter(conllInputFile));
    try {
        for (String posSentence : posSentences) {
            posSentence = replaceSentenceWithPTBWords(posSentence);
            ArrayList<String> words = new ArrayList<String>();
            ArrayList<String> pos = new ArrayList<String>();
            ArrayList<String> parents = new ArrayList<String>();
            ArrayList<String> labels = new ArrayList<String>();
            StringTokenizer st = new StringTokenizer(posSentence.trim());
            while (st.hasMoreTokens()) {
                String token = st.nextToken();
                int lastIndex = token.lastIndexOf('_');
                String word = token.substring(0, lastIndex);
                String POS = token.substring(lastIndex + 1);
                words.add(word);
                pos.add(POS);
                parents.add("0");
                labels.add("SUB");
            }
            writeStuff(bWriter, words, pos, parents, labels);
        }
    } finally {
        IOUtils.closeQuietly(bWriter);
    }
}

From source file:fr.sanofi.fcl4transmart.controllers.listeners.geneExpression.SetSiteIdListener.java

@Override
public void handleEvent(Event event) {
    // TODO Auto-generated method stub
    Vector<String> values = this.setSiteIdUI.getValues();
    Vector<String> samples = this.setSiteIdUI.getSamples();
    File file = new File(this.dataType.getPath().toString() + File.separator
            + this.dataType.getStudy().toString() + ".subject_mapping.tmp");
    File stsmf = ((GeneExpressionData) this.dataType).getStsmf();
    if (stsmf == null) {
        this.setSiteIdUI.displayMessage("Error: no subject to sample mapping file");
    }//from w  w  w.j  a  v  a 2  s  .  com
    try {
        FileWriter fw = new FileWriter(file);
        BufferedWriter out = new BufferedWriter(fw);
        out.write(
                "study_id\tsite_id\tsubject_id\tSAMPLE_ID\tPLATFORM\tTISSUETYPE\tATTR1\tATTR2\tcategory_cd\n");

        try {
            BufferedReader br = new BufferedReader(new FileReader(stsmf));
            String line = br.readLine();
            while ((line = br.readLine()) != null) {
                String[] fields = line.split("\t", -1);
                String sample = fields[3];
                String site;
                if (samples.contains(sample)) {
                    site = values.get(samples.indexOf(sample));
                } else {
                    br.close();
                    return;
                }
                out.write(fields[0] + "\t" + site + "\t" + fields[2] + "\t" + sample + "\t" + fields[4] + "\t"
                        + fields[5] + "\t" + fields[6] + "\t" + fields[7] + "\t" + fields[8] + "\n");
            }
            br.close();
        } catch (Exception e) {
            this.setSiteIdUI.displayMessage("Error: " + e.getLocalizedMessage());
            out.close();
            e.printStackTrace();
        }
        out.close();
        try {
            File fileDest;
            if (stsmf != null) {
                String fileName = stsmf.getName();
                stsmf.delete();
                fileDest = new File(this.dataType.getPath() + File.separator + fileName);
            } else {
                fileDest = new File(this.dataType.getPath() + File.separator
                        + this.dataType.getStudy().toString() + ".subject_mapping");
            }
            FileUtils.moveFile(file, fileDest);
            ((GeneExpressionData) this.dataType).setSTSMF(fileDest);
        } catch (IOException ioe) {
            this.setSiteIdUI.displayMessage("File error: " + ioe.getLocalizedMessage());
            return;
        }
    } catch (Exception e) {
        this.setSiteIdUI.displayMessage("Error: " + e.getLocalizedMessage());
        e.printStackTrace();
    }
    this.setSiteIdUI.displayMessage("Subject to sample mapping file updated");
    WorkPart.updateSteps();
    WorkPart.updateFiles();
}

From source file:net.mohatu.bloocoin.miner.Miner.java

public void mine() throws NoSuchAlgorithmException {
    // String testString = "dx3NAa"; //dx3NAa257363
    while (Main.getStatus()) {
        String startString = randomString();
        System.out.println("Starting: " + startString);

        for (int counter = 0; counter <= 10000000; counter++) {
            Main.updateCounter();//from   www  . j a  v  a 2  s .  c om
            String currentString = startString + counter;
            String hash = DigestUtils.sha512Hex(currentString);

            if (hash.startsWith(difficulty)) {
                new Thread(new Submitter(hash, currentString)).start();

                Main.updateSolved(currentString);
                System.out.println("Success: " + currentString);

                try {
                    PrintWriter out = new PrintWriter(new BufferedWriter(
                            new FileWriter(System.getProperty("user.home") + "/.bloocoin/solved.dat", true)));
                    out.println(currentString);
                    out.close();
                } catch (IOException e) {
                    // Error
                    System.out.println("Unable to save to BLC_Solved.txt, check permissions.");
                }

            }

            if (!Main.getStatus()) {
                counter = 10000000;
                System.out.println("STOPPING");
            }
        }
    }
}

From source file:io.druid.data.input.impl.PrefetchableTextFilesFirehoseFactoryTest.java

@BeforeClass
public static void setup() throws IOException {
    testDir = File.createTempFile(PrefetchableTextFilesFirehoseFactoryTest.class.getSimpleName(), "testDir");
    FileUtils.forceDelete(testDir);//from  ww w.j  a v  a2 s . c o  m
    FileUtils.forceMkdir(testDir);

    firehoseTempDir = File.createTempFile(PrefetchableTextFilesFirehoseFactoryTest.class.getSimpleName(),
            "baseDir");
    FileUtils.forceDelete(firehoseTempDir);
    FileUtils.forceMkdir(firehoseTempDir);

    for (int i = 0; i < 10; i++) {
        // Each file is 1390 bytes
        try (final Writer writer = new BufferedWriter(new FileWriter(new File(testDir, "test_" + i)))) {
            for (int j = 0; j < 100; j++) {
                final String a = (20171220 + i) + "," + i + "," + j + "\n";
                writer.write(a);
            }
        }
    }
}

From source file:chibi.gemmaanalysis.ExpressionDataLoader.java

public void writeExpressionDataToFile(String paraFileName) {
    try (BufferedWriter writer = new BufferedWriter(new FileWriter(this.analysisResultsPath + paraFileName))) {
        writer.write("Experiment Name: " + this.experimentName + "\n");
        writer.write("Accession: " + this.experiment.getAccession().getAccession() + "\n");
        writer.write("Name: " + this.experiment.getName() + "\n");
        writer.write("Description: " + this.experiment.getDescription() + "\n");
        writer.write("Source: " + this.experiment.getSource() + "\n");

        for (DesignElementDataVector dataVector : this.designElementDataVectors) {
            CompositeSequence designElement = dataVector.getDesignElement();
            String probId = designElement.getName();
            byte[] expressionByteData = dataVector.getData();
            ByteArrayConverter byteConverter = new ByteArrayConverter();
            double[] expressionData = byteConverter.byteArrayToDoubles(expressionByteData);
            writer.write(probId + "\t");
            for (int i = 0; i < expressionData.length; i++)
                writer.write(expressionData[i] + "\t");
            writer.write(dataVector.getQuantitationType().getName() + "\t");
            writer.write(dataVector.getQuantitationType().getRepresentation() + "\t");
            writer.write(dataVector.getQuantitationType().getScale().getValue() + "\t");
            writer.write(dataVector.getQuantitationType().getType().getValue() + "\t");
            writer.write("\n");
        }//from   w  ww. ja  va  2s  . c  o  m
    } catch (IOException e) {
        log.error("Error in write data into file");
    }
}

From source file:fr.sanofi.fcl4transmart.controllers.listeners.geneExpression.SetPlatformsListener.java

@Override
public void handleEvent(Event event) {
    // TODO Auto-generated method stub
    Vector<String> values = this.setPlatformsUI.getValues();
    Vector<String> samples = this.setPlatformsUI.getSamples();
    File file = new File(this.dataType.getPath().toString() + File.separator
            + this.dataType.getStudy().toString() + ".subject_mapping.tmp");
    File stsmf = ((GeneExpressionData) this.dataType).getStsmf();
    if (stsmf == null) {
        this.setPlatformsUI.displayMessage("Error: no subject to sample mapping file");
    }//  w ww  .j a  va  2s  .co  m
    try {
        FileWriter fw = new FileWriter(file);
        BufferedWriter out = new BufferedWriter(fw);
        out.write(
                "study_id\tsite_id\tsubject_id\tSAMPLE_ID\tPLATFORM\tTISSUETYPE\tATTR1\tATTR2\tcategory_cd\n");

        try {
            BufferedReader br = new BufferedReader(new FileReader(stsmf));
            String line = br.readLine();
            while ((line = br.readLine()) != null) {
                String[] fields = line.split("\t", -1);
                String sample = fields[3];
                String platform;
                if (samples.contains(sample)) {
                    platform = values.get(samples.indexOf(sample));
                } else {
                    br.close();
                    return;
                }
                out.write(fields[0] + "\t" + fields[1] + "\t" + fields[2] + "\t" + sample + "\t" + platform
                        + "\t" + fields[5] + "\t" + fields[6] + "\t" + fields[7] + "\t" + fields[8] + "\n");
            }
            br.close();
        } catch (Exception e) {
            this.setPlatformsUI.displayMessage("Error: " + e.getLocalizedMessage());
            out.close();
            e.printStackTrace();
        }
        out.close();
        try {
            File fileDest;
            if (stsmf != null) {
                String fileName = stsmf.getName();
                stsmf.delete();
                fileDest = new File(this.dataType.getPath() + File.separator + fileName);
            } else {
                fileDest = new File(this.dataType.getPath() + File.separator
                        + this.dataType.getStudy().toString() + ".subject_mapping");
            }
            FileUtils.moveFile(file, fileDest);
            ((GeneExpressionData) this.dataType).setSTSMF(fileDest);
        } catch (IOException ioe) {
            this.setPlatformsUI.displayMessage("File error: " + ioe.getLocalizedMessage());
            return;
        }
    } catch (Exception e) {
        this.setPlatformsUI.displayMessage("Error: " + e.getLocalizedMessage());
        e.printStackTrace();
    }
    this.setPlatformsUI.displayMessage("Subject to sample mapping file updated");
    WorkPart.updateSteps();
    WorkPart.updateFiles();
}