Example usage for java.io BufferedWriter append

List of usage examples for java.io BufferedWriter append

Introduction

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

Prototype

public Writer append(CharSequence csq) throws IOException 

Source Link

Document

Appends the specified character sequence to this writer.

Usage

From source file:com.pieframework.runtime.utils.azure.CsdefGenerator.java

private void printStartupTasks(BufferedWriter out, Role r) {
    //print startup tasks (bootstrap services)
    try {//from   w  ww .  j  a va  2 s  .c  o m
        List<String> startupTasks = new ArrayList<String>();
        for (String key : r.getChildren().keySet()) {
            Service service = null;
            if (r.getChildren().get(key) instanceof Service) {
                service = (Service) r.getChildren().get(key);
                if (service != null && service.getProps().get("type").equalsIgnoreCase("bootstrap")) {
                    if (service.getProps().get("startupTask") != null) {
                        startupTasks.add(service.getProps().get("startupTask"));
                    }
                }
            }
        }

        out.append("<Startup>");
        for (String task : startupTasks) {
            out.append("<Task commandLine=\"" + task
                    + "\" executionContext=\"elevated\" taskType=\"background\"></Task>");
        }
        out.append("</Startup>");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:edu.isi.pfindr.learn.util.PairsFileIO.java

private void getGoldClassForPairs(String inputFilePath) {

    LinkedMap originalTestPairsClassMap = new LinkedMap();
    String originalTestPairsFile = "data/cohort1/bio_nlp/cohort1_s_test_pairs.txt";
    BufferedReader br = null;//from   ww  w .j a  va2s.  c o  m
    String[] lineArray;
    String thisLine;
    try {
        br = new BufferedReader(new FileReader(originalTestPairsFile));
        while ((thisLine = br.readLine()) != null) {
            thisLine = thisLine.trim();
            if (thisLine.equals(""))
                continue;

            lineArray = thisLine.split("\t");
            originalTestPairsClassMap.put(lineArray[0] + "\t" + lineArray[1], lineArray[2]);
        }
    } catch (IOException io) {
        try {
            if (br != null)
                br.close();
            io.printStackTrace();
        } catch (IOException e) {
            System.out.println("Problem occured while closing output stream " + br);
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    List<String> phenotypeList = null;
    StringBuffer resultFileBuffer = new StringBuffer();

    //Read the pairs file, and write the pairs with class from actual test file
    try {
        BufferedWriter resultPairsWriter = new BufferedWriter(
                new FileWriter(inputFilePath.split("\\.")[0] + "_with_gold_class.txt"));
        phenotypeList = FileUtils.readLines(new File(inputFilePath));

        for (int i = 0; i < phenotypeList.size(); i++) {

            lineArray = phenotypeList.get(i).split("\t");
            resultFileBuffer.append(lineArray[0]).append("\t").append(lineArray[1]).append("\t")
                    .append(originalTestPairsClassMap.get(lineArray[0] + "\t" + lineArray[1])).append("\n");
        }

        resultPairsWriter.append(resultFileBuffer.toString());
        resultFileBuffer.setLength(0);
        resultPairsWriter.flush();

    } catch (IOException e) {
        System.out.println("Error while reading/writing file with pairs" + e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:ibme.sleepap.recording.SignalsRecorder.java

void writeRawActigraphy() {
    // Writes Accelerometer data
    try {//from  w ww. j  ava2s . c  om
        BufferedWriter out = new BufferedWriter(new FileWriter(accelerationFile, true));
        out.append(String.valueOf(accelerometerCurrentTime) + ",");
        out.append(String.valueOf(latestAccelerometerEventValues[0]) + ",");
        out.append(String.valueOf(latestAccelerometerEventValues[1]) + ",");
        out.append(String.valueOf(latestAccelerometerEventValues[2]) + "\n");
        out.flush();
        out.close();
    } catch (IOException e) {
        Log.e(Constants.CODE_APP_TAG, "Error writing raw actigraphy data to file", e);
    }
}

From source file:org.ihtsdo.classifier.ClassificationRunner.java

/**
 * Write inferred rel.//from  w w w.  j  a  v  a  2 s.c o  m
 *
 * @param infRels the inf rels
 * @throws java.io.IOException Signals that an I/O exception has occurred.
 */
private void writeInferredRel(List<Relationship> infRels) throws IOException {

    // STATISTICS COUNTERS
    int countConSeen = 0;

    FileOutputStream fos = new FileOutputStream(newInferredRelationships);
    OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
    BufferedWriter bw = new BufferedWriter(osw);

    bw.append("id");
    bw.append("\t");
    bw.append("effectiveTime");
    bw.append("\t");
    bw.append("active");
    bw.append("\t");
    bw.append("moduleId");
    bw.append("\t");
    bw.append("sourceId");
    bw.append("\t");
    bw.append("destinationId");
    bw.append("\t");
    bw.append("relationshipGroup");
    bw.append("\t");
    bw.append("typeId");
    bw.append("\t");
    bw.append("characteristicTypeId");
    bw.append("\t");
    bw.append("modifierId");
    bw.append("\r\n");

    Collections.sort(infRels);

    // Typically, B is the SnoRocket Results Set (for newly inferred)
    Iterator<Relationship> itRel = infRels.iterator();

    Relationship infRel = null;
    boolean done = false;
    if (itRel.hasNext()) {
        infRel = itRel.next();
    } else {
        done = true;
    }

    // BY SORT ORDER, LOWER NUMBER ADVANCES FIRST

    while (!done) {
        if (++countConSeen % 25000 == 0) {
            logger.info("::: [Snorocket] write inferred rels @ #\t" + countConSeen);
        }
        writeRel(bw, infRel);

        if (itRel.hasNext()) {
            infRel = itRel.next();
        } else {
            done = true;
        }

    }
    bw.close();
    bw = null;
    osw = null;
    fos = null;
}

From source file:com.termmed.statistics.Processor.java

/**
 * Prints the report./*  w  ww  .j  a  v a2s .  c  om*/
 *
 * @param bw the bw
 * @param tableMap the table map
 * @throws Exception the exception
 */
private void printReport(BufferedWriter bw, OutputFileTableMap tableMap) throws Exception {

    SQLStatementExecutor executor = new SQLStatementExecutor(connection);

    for (SelectTableMap select : tableMap.getSelect()) {
        String query = "Select * from " + select.getTableName();
        if (executor.executeQuery(query, null)) {
            ResultSet rs = executor.getResultSet();

            if (rs != null) {
                ResultSetMetaData meta = rs.getMetaData();
                while (rs.next()) {
                    for (int i = 0; i < meta.getColumnCount(); i++) {
                        if (rs.getObject(i + 1) != null) {
                            bw.append(rs.getObject(i + 1).toString());
                        } else {
                            bw.append("");
                        }
                        if (i + 1 < meta.getColumnCount()) {
                            bw.append(",");
                        } else {
                            bw.append("\r\n");
                        }
                    }
                }

                meta = null;
                rs.close();
            }
        }
    }
    executor = null;
}

From source file:de.tudarmstadt.ukp.clarin.webanno.automation.util.AutomationUtil.java

public static void generateTrainDocument(MiraTemplate aTemplate, RepositoryService aRepository,
        AnnotationService aAnnotationService, AutomationService aAutomationService, UserDao aUserDao,
        boolean aBase) throws IOException, UIMAException, ClassNotFoundException, AutomationException {
    File miraDir = aAutomationService.getMiraDir(aTemplate.getTrainFeature());
    if (!miraDir.exists()) {
        FileUtils.forceMkdir(miraDir);/*from w ww  .  ja va 2  s. c o m*/
    }

    String username = SecurityContextHolder.getContext().getAuthentication().getName();
    User user = aUserDao.get(username);
    AnnotationFeature feature = aTemplate.getTrainFeature();
    boolean documentChanged = false;
    // A. training document for other train layers were changed
    for (AnnotationFeature otherrFeature : aTemplate.getOtherFeatures()) {
        for (SourceDocument document : aRepository
                .listSourceDocuments(aTemplate.getTrainFeature().getProject())) {
            if (!document.isProcessed() && document.getFeature() != null
                    && document.getFeature().equals(otherrFeature)) {
                documentChanged = true;
                break;
            }
        }
    }
    // B. Training document for the main training layer were changed
    for (SourceDocument document : aRepository.listSourceDocuments(feature.getProject())) {
        if (!document.isProcessed()
                && (document.getFeature() != null && document.getFeature().equals(feature))) {
            documentChanged = true;
            break;
        }
    }
    // C. New Curation document arrives
    for (SourceDocument document : aRepository.listSourceDocuments(feature.getProject())) {
        if (!document.isProcessed() && document.getState().equals(SourceDocumentState.CURATION_FINISHED)) {
            documentChanged = true;
            break;
        }
    }
    // D. tab-sep training documents
    for (SourceDocument document : aAutomationService
            .listTabSepDocuments(aTemplate.getTrainFeature().getProject())) {
        if (!document.isProcessed() && document.getFeature() != null && document.getFeature().equals(feature)) {
            documentChanged = true;
            break;
        }
    }
    if (!documentChanged) {
        return;
    }
    File trainFile;
    if (aBase) {
        trainFile = new File(miraDir, feature.getLayer().getId() + "-" + feature.getId() + ".train.ft");
    } else {
        trainFile = new File(miraDir, feature.getLayer().getId() + "-" + feature.getId() + ".train.base");
    }

    AutomationStatus status = aAutomationService.getAutomationStatus(aTemplate);

    BufferedWriter trainOut = new BufferedWriter(new FileWriter(trainFile));
    AutomationTypeAdapter adapter = (AutomationTypeAdapter) TypeUtil.getAdapter(aAnnotationService,
            feature.getLayer());
    // Training documents (Curated or webanno-compatible imported ones - read using UIMA)
    for (SourceDocument sourceDocument : aRepository.listSourceDocuments(feature.getProject())) {
        if ((sourceDocument.isTrainingDocument() && sourceDocument.getFeature() != null
                && sourceDocument.getFeature().equals(feature))) {
            JCas jCas = aRepository.readAnnotationCas(sourceDocument, user);
            for (Sentence sentence : select(jCas, Sentence.class)) {
                if (aBase) {// base training document
                    trainOut.append(getMiraLine(sentence, null, adapter).toString() + "\n");
                } else {// training document with other features
                    trainOut.append(getMiraLine(sentence, feature, adapter).toString() + "\n");
                }
            }
            sourceDocument.setProcessed(!aBase);
            if (!aBase) {
                status.setTrainDocs(status.getTrainDocs() - 1);
            }
        } else if (sourceDocument.getState().equals(SourceDocumentState.CURATION_FINISHED)) {
            JCas jCas = aRepository.readCurationCas(sourceDocument);
            for (Sentence sentence : select(jCas, Sentence.class)) {
                if (aBase) {// base training document
                    trainOut.append(getMiraLine(sentence, null, adapter).toString() + "\n");
                } else {// training document with other features
                    trainOut.append(getMiraLine(sentence, feature, adapter).toString() + "\n");
                }
            }
            sourceDocument.setProcessed(!aBase);
            if (!aBase) {
                status.setTrainDocs(status.getTrainDocs() - 1);
            }
        }
    }
    // Tab-sep documents to be used as a target layer train document
    for (SourceDocument document : aAutomationService.listTabSepDocuments(feature.getProject())) {
        if (document.getFormat().equals(WebAnnoConst.TAB_SEP) && document.getFeature() != null
                && document.getFeature().equals(feature)) {
            File tabSepFile = new File(aRepository.getDocumentFolder(document), document.getName());
            LineIterator it = IOUtils.lineIterator(new FileReader(tabSepFile));
            while (it.hasNext()) {
                String line = it.next();
                if (line.trim().equals("")) {
                    trainOut.append("\n");
                } else {
                    StringTokenizer st = new StringTokenizer(line, "\t");
                    if (st.countTokens() != 2) {
                        trainOut.close();
                        throw new AutomationException("This is not a valid TAB-SEP document");
                    }
                    if (aBase) {
                        trainOut.append(getMiraLineForTabSep(st.nextToken(), ""));
                    } else {
                        trainOut.append(getMiraLineForTabSep(st.nextToken(), st.nextToken()));
                    }
                }
            }
        }
    }
    trainOut.close();
}

From source file:com.alta189.cyborg.api.util.config.ini.IniConfiguration.java

protected void saveFromNodes(Map<String, ConfigurationNode> nodes) throws ConfigurationException {
    Writer rawWriter = null;//from w w  w  .j  a v  a 2  s.c  o  m
    BufferedWriter writer = null;
    try {
        rawWriter = getWriter();
        writer = new BufferedWriter(rawWriter);

        List<ConfigurationNode> childlessNodes = new ArrayList<ConfigurationNode>(),
                sectionNodes = new ArrayList<ConfigurationNode>();
        for (ConfigurationNode node : nodes.values()) {
            if (node.hasChildren()) {
                sectionNodes.add(node);
            } else {
                childlessNodes.add(node);
            }
        }

        if (childlessNodes.size() > 0) {
            writeNodeSection(writer, childlessNodes);
        }

        for (Iterator<ConfigurationNode> i = sectionNodes.iterator(); i.hasNext();) {
            ConfigurationNode node = i.next();
            String[] comment = getComment(node);
            if (comment != null) {
                for (String line : comment) {
                    writer.append(getPreferredCommentChar()).append(" ").append(line).append(LINE_SEPARATOR);
                }
            }
            writer.append('[').append(node.getPathElements()[0]).append(']').append(LINE_SEPARATOR);
            writeNodeSection(writer, node.getChildren().values());
            if (i.hasNext()) {
                writer.append(LINE_SEPARATOR);
            }
        }
    } catch (IOException e) {
        throw new ConfigurationException(e);
    } finally {
        if (writer != null) {
            try {
                writer.flush();
            } catch (IOException ignore) {
            }
        }
        if (rawWriter != null) {
            try {
                rawWriter.flush();
                rawWriter.close();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:com.flowpowered.cerealization.config.ini.IniConfiguration.java

@Override
protected void saveFromNodes(Map<String, ConfigurationNode> nodes) throws ConfigurationException {
    Writer rawWriter = null;/*from  w  ww.j a v  a 2s . c om*/
    BufferedWriter writer = null;
    try {
        rawWriter = getWriter();
        writer = new BufferedWriter(rawWriter);

        List<ConfigurationNode> childlessNodes = new ArrayList<ConfigurationNode>(),
                sectionNodes = new ArrayList<ConfigurationNode>();
        for (ConfigurationNode node : nodes.values()) {
            if (node.hasChildren()) {
                sectionNodes.add(node);
            } else {
                childlessNodes.add(node);
            }
        }

        if (childlessNodes.size() > 0) {
            writeNodeSection(writer, childlessNodes);
        }

        for (Iterator<ConfigurationNode> i = sectionNodes.iterator(); i.hasNext();) {
            ConfigurationNode node = i.next();
            String[] comment = getComment(node);
            if (comment != null) {
                for (String line : comment) {
                    writer.append(getPreferredCommentChar()).append(" ").append(line).append(LINE_SEPARATOR);
                }
            }
            writer.append('[').append(node.getPathElements()[0]).append(']').append(LINE_SEPARATOR);
            writeNodeSection(writer, node.getChildren().values());
            if (i.hasNext()) {
                writer.append(LINE_SEPARATOR);
            }
        }
    } catch (IOException e) {
        throw new ConfigurationException(e);
    } finally {
        if (writer != null) {
            try {
                writer.flush();
            } catch (IOException ignore) {
            }
        }
        if (rawWriter != null) {
            try {
                rawWriter.flush();
                rawWriter.close();
            } catch (IOException ignore) {
            }
        }
    }
}

From source file:com.ibm.bi.dml.test.utils.TestUtils.java

/**
 * <p>/*from  ww w.j  a va2 s .com*/
 * Writes a matrix to a file using the text format.
 * </p>
 * 
 * @param file
 *            file name
 * @param matrix
 *            matrix
 * @param isR
 *            when true, writes a R matrix to disk
 * 
 */
public static void writeTestMatrix(String file, double[][] matrix, boolean isR) {
    try {
        //create outputstream to HDFS / FS and writer
        DataOutputStream out = null;
        if (!isR) {
            FileSystem fs = FileSystem.get(conf);
            out = fs.create(new Path(file), true);
        } else {
            out = new DataOutputStream(new FileOutputStream(file));
        }

        BufferedWriter pw = new BufferedWriter(new OutputStreamWriter(out));

        //write header
        if (isR) {
            /** add R header */
            pw.append("%%MatrixMarket matrix coordinate real general\n");
            pw.append("" + matrix.length + " " + matrix[0].length + " " + matrix.length * matrix[0].length
                    + "\n");
        }

        //writer actual matrix
        StringBuilder sb = new StringBuilder();
        boolean emptyOutput = true;
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                if (matrix[i][j] == 0)
                    continue;
                sb.append(i + 1);
                sb.append(' ');
                sb.append(j + 1);
                sb.append(' ');
                sb.append(matrix[i][j]);
                sb.append('\n');
                pw.append(sb.toString());
                sb.setLength(0);
                emptyOutput = false;
            }
        }

        //writer dummy entry if empty
        if (emptyOutput)
            pw.append("1 1 " + matrix[0][0]);

        //close writer and streams
        pw.close();
        out.close();
    } catch (IOException e) {
        fail("unable to write test matrix (" + file + "): " + e.getMessage());
    }
}

From source file:com.wheelphone.remotemini.WheelphoneRemoteMini.java

void appendLog(String fileName, String text, boolean clearFile) {
    File logFile = new File("sdcard/" + fileName);
    if (!logFile.exists()) {
        try {/*from   w w w .j  ava 2 s  .com*/
            logFile.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        if (clearFile) {
            logFile.delete();
            try {
                logFile.createNewFile();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    try {
        //BufferedWriter for performance, true to set append to file flag
        BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
        buf.append(text);
        buf.newLine();
        buf.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}