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:de.dfki.km.perspecting.obie.experiments.PhraseExperiment.java

/**
 * Test method for// w  w  w .  j  a va  2  s. c o  m
 * {@link de.dfki.km.perspecting.obie.dixi.service.SimpleScobieService#extractInformationFromURL(java.lang.String, java.lang.String)}
 * .
 */
@Test
public void analyseTokenPhraseFrequencies() {
    final String template = "SELECT * WHERE {?s ?p ?o}";

    try {
        final BufferedWriter bw = new BufferedWriter(
                new FileWriter($SCOOBIE_HOME + "results/token_phrase_frequency_wikipedia.csv"));

        final String randomWikipediaPage = "http://en.wikipedia.org/wiki/Special:Random";

        bw.append("tok in doc\tnp in doc\ttok in nps\tdistinct tok in nps\tdistinct tok in doc");
        for (int i = 0; i < 100; i++) {

            Document document = pipeline.createDocument(FileUtils.toFile(new URL(randomWikipediaPage)),
                    new URI(randomWikipediaPage), MediaType.HTML, template, Language.EN);

            for (int step = 0; pipeline.hasNext(step) && step <= 5; step = pipeline.execute(step, document)) {
                System.out.println(step);
            }

            HashSet<String> wordsOfPhrases = new HashSet<String>();
            HashSet<String> wordsOfDocument = new HashSet<String>();

            for (Token token : document.getTokens()) {
                wordsOfDocument.add(token.toString());
            }

            int count = 0;
            for (TokenSequence<String> np : document.getNounPhrases()) {
                String[] words = np.toString().split("[\\s]+");
                count += words.length;
                wordsOfPhrases.addAll(Arrays.asList(words));
            }

            bw.append(document.getTokens().size() + "\t" + document.getNounPhrases().size() + "\t" + count
                    + "\t" + wordsOfPhrases.size() + "\t" + wordsOfDocument.size());
            bw.newLine();

        }
        bw.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try {
        final BufferedWriter bw = new BufferedWriter(
                new FileWriter($SCOOBIE_HOME + "results/token_phrase_frequency_reuters.csv"));

        final TextCorpus corpus = new TextCorpus(new File("../corpora/reuters/reuters.zip"), MediaType.ZIP,
                MediaType.HTML, Language.EN);

        bw.append("tok in doc\tnp in doc\ttok in nps\tdistinct tok in nps\tdistinct tok in doc");

        corpus.forEach(new DocumentProcedure<URI>() {

            @Override
            public URI process(Reader reader, URI uri) throws Exception {

                Document document = pipeline.createDocument(reader, uri, corpus.getMediatype(), template,
                        corpus.getLanguage());

                for (int step = 0; pipeline.hasNext(step)
                        && step <= 5; step = pipeline.execute(step, document)) {
                    System.out.println(step);
                }

                HashSet<String> wordsOfPhrases = new HashSet<String>();
                HashSet<String> wordsOfDocument = new HashSet<String>();

                for (Token token : document.getTokens()) {
                    wordsOfDocument.add(token.toString());
                }

                int count = 0;
                for (TokenSequence<String> np : document.getNounPhrases()) {
                    String[] words = np.toString().split("[\\s]+");
                    count += words.length;
                    wordsOfPhrases.addAll(Arrays.asList(words));
                }

                bw.append(document.getTokens().size() + "\t" + document.getNounPhrases().size() + "\t" + count
                        + "\t" + wordsOfPhrases.size() + "\t" + wordsOfDocument.size());
                bw.newLine();
                return uri;
            }
        });

        bw.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:cn.org.once.cstack.service.impl.ScriptingServiceImpl.java

public void execute(String scriptContent, String login, String password) throws ServiceException {
    logger.info(scriptContent);/*from  w ww  .ja va  2s  .  com*/

    File tmpFile = null;
    FileWriter fileWriter = null;
    BufferedWriter writer = null;
    ProcessBuilder processBuilder = null;
    try {
        tmpFile = File.createTempFile(login, ".cmdFile");
        fileWriter = new FileWriter(tmpFile);
        writer = new BufferedWriter(fileWriter);
        String commandConnect = CONNECT_CMD.replace("#USER", login).replace("#PASSWORD", password)
                .replace("#HOST", host);
        logger.debug(commandConnect);
        writer.append(commandConnect);
        writer.newLine();
        writer.append(scriptContent);
        writer.newLine();
        writer.append(DISCONNECT_CMD);
        writer.flush();
        logger.debug(writer.toString());

        File fileCLI = new File(pathCLI);
        if (!fileCLI.exists()) {
            System.out.println("Error ! ");
            StringBuilder msgError = new StringBuilder(512);
            msgError.append(
                    "\nPlease run manually (1) : mkdir -p " + pathCLI.substring(0, pathCLI.lastIndexOf("/")));
            msgError.append(
                    "\nPlease run manually (2) : wget https://github.com/Treeptik/cloudunit/releases/download/1.0/CloudUnitCLI.jar -O "
                            + pathCLI);
            throw new ServiceException(msgError.toString());
        }

        processBuilder = new ProcessBuilder("java", "-jar", pathCLI, "--cmdfile", tmpFile.getAbsolutePath());
        processBuilder.redirectErrorStream(true);
        Process process = processBuilder.start();

        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = "";
        try {
            while ((line = reader.readLine()) != null) {
                logger.info(line);
                if (line.contains("not found"))
                    throw new ServiceException("Syntax error : " + line);
                if (line.contains("Invalid or corrupt jarfile"))
                    throw new ServiceException("Invalid or corrupt jarfile");
            }
        } finally {
            reader.close();
        }

    } catch (IOException e) {
        StringBuilder msgError = new StringBuilder(512);
        msgError.append("login=").append(login);
        msgError.append(", password=").append(password);
        msgError.append(", scriptContent=").append(scriptContent);
        logger.error(msgError.toString(), e);
    } finally {
        try {
            fileWriter.close();
        } catch (Exception ignore) {
        }
        try {
            writer.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:ch.vorburger.webdriver.reporting.TestCaseReportWriter.java

public void writeToFile(String message) {
    // TODO Use something in org.apache.commons.io.FileUtils which does this..
    if (message.indexOf(END_TEST) > 0) {
        BufferedWriter bufferedWriter = null;
        try {//from  www  .  jav a  2  s  . c o  m
            bufferedWriter = new BufferedWriter(new FileWriter(getLogFile().getPath(), true));
            bufferedWriter.newLine();
            bufferedWriter.append(message);
        } catch (IOException e) {
            // e.printStackTrace();
        } finally {
            try {
                if (bufferedWriter != null) {
                    bufferedWriter.flush();
                    bufferedWriter.close();
                }
            } catch (IOException ex) {
                // ex.printStackTrace();
            }
        }
    }
}

From source file:org.openhie.openempi.matching.fellegisunter.ProbabilisticMatchingServiceBase.java

public List<LeanRecordPair> orderRecordPairsByWeight(List<LeanRecordPair> pairs, boolean writeStat,
        String pathPrefix) {/*from  www .  j a  va2s  .com*/
    Collections.sort(pairs, new RecordPairComparatorByWeight());
    if (writeStat) {
        try {
            FileWriter fw = new FileWriter(pathPrefix + " " + Constants.WEIGHTS_FILE_NAME);
            BufferedWriter bw = new BufferedWriter(fw);
            try {
                for (LeanRecordPair pair : pairs) {
                    bw.append(Double.toString(pair.getWeight())); // TODO: write some kind of ids
                    bw.newLine(); // System.getProperty("line.separator")
                }
            } finally {
                bw.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return pairs;
}

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

/**
 * Adds the header.//from www.  j a  v  a 2s . c o m
 *
 * @param bw the bw
 * @param tableMap the table map
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void addHeader(BufferedWriter bw, OutputFileTableMap tableMap) throws IOException {
    bw.append(tableMap.getReportHeader());
    bw.append("\r\n");
}

From source file:com.qcadoo.plugins.qcadooExport.internal.ExportToCsvController.java

@Monitorable(threshold = 500)
@ResponseBody/*from w w  w. j a v a  2s . c  o m*/
@RequestMapping(value = { CONTROLLER_PATH }, method = RequestMethod.POST)
public Object generateCsv(@PathVariable(PLUGIN_IDENTIFIER_VARIABLE) final String pluginIdentifier,
        @PathVariable(VIEW_NAME_VARIABLE) final String viewName, @RequestBody final JSONObject body,
        final Locale locale) {
    try {
        changeMaxResults(body);

        ViewDefinitionState state = crudService.invokeEvent(pluginIdentifier, viewName, body, locale);

        GridComponent grid = (GridComponent) state.getComponentByReference("grid");

        String date = DateFormat.getDateInstance().format(new Date());
        File file = fileService.createExportFile("export_" + grid.getName() + "_" + date + ".csv");

        BufferedWriter output = null;

        try {
            output = new BufferedWriter(
                    new OutputStreamWriter(new FileOutputStream(file), Charset.forName("UTF-8")));

            boolean firstName = true;

            for (String name : grid.getColumnNames().values()) {
                if (firstName) {
                    firstName = false;
                } else {
                    output.append(EXPORTED_DOCUMENT_SEPARATOR);
                }
                output.append("\"").append(normalizeString(name)).append("\"");
            }

            output.append("\n");

            List<Map<String, String>> rows;
            if (grid.getSelectedEntitiesIds().isEmpty()) {
                rows = grid.getColumnValuesOfAllRecords();
            } else {
                rows = grid.getColumnValuesOfSelectedRecords();
            }

            for (Map<String, String> row : rows) {
                boolean firstValue = true;
                for (String value : row.values()) {
                    if (firstValue) {
                        firstValue = false;
                    } else {
                        output.append(EXPORTED_DOCUMENT_SEPARATOR);
                    }
                    output.append("\"").append(normalizeString(value)).append("\"");
                }

                output.append("\n");
            }

            output.flush();
        } catch (IOException e) {
            throw new IllegalStateException(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(output);
        }

        state.redirectTo(fileService.getUrl(file.getAbsolutePath()) + "?clean", true, false);

        return crudService.renderView(state);
    } catch (JSONException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

From source file:com.roamtouch.menuserver.utils.FileUtils.java

public void storeAboutLog(String text) {

    File logFolder = new File(app.getSDCARD() + "/httpd/media/about");
    if (!logFolder.exists()) {
        logFolder.mkdir();/*from   w w w.  j  a  v a  2 s.  c om*/
    }

    String dateFormat = app.getTimeDate("dd_MM_yyyy");

    File logFile = new File(
            logFolder.toString() + "/" + "About_" + getWeekDay() + "-" + dateFormat + "" + ".txt");
    if (!logFile.exists()) {
        try {
            logFile.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
        buf.append(text);
        buf.newLine();
        buf.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.talend.dataprofiler.core.migration.impl.ModelIndicatorTdColumnToModelElementTask.java

/**
 * //from   w w w.j  a  va 2 s  . c om
 * DOC mzhao string replacement method.
 * 
 * @param srcFile
 * @return
 */
private void replace(File srcFile) throws Throwable {
    File destFile = new File(srcFile.getAbsolutePath() + MIGRATION_FILE_EXT);

    BufferedReader fileReader = new BufferedReader(new FileReader(srcFile));
    BufferedWriter fileWriter = new BufferedWriter(new FileWriter(destFile));

    while (fileReader.ready()) {
        String line = fileReader.readLine();
        if (StringUtils.contains(line, TO_BE_RPLACED_STRING_PREFIX)
                && !StringUtils.contains(line, REPLACED_STRING)) {
            line = StringUtils.replace(line, TO_BE_RPLACED_STRING_PREFIX,
                    TO_BE_RPLACED_STRING_PREFIX + REPLACED_STRING);
            log.debug(line);
        }
        fileWriter.append(line);
        fileWriter.newLine();
    }
    fileWriter.flush();
    fileWriter.close();
    fileWriter = null;
    fileReader.close();
    fileReader = null;
}

From source file:org.kalypso.wspwin.core.WspWinZustand.java

public void write(final File wspwinDir) throws IOException {
    final WspWinProject wspWinProject = new WspWinProject(wspwinDir);
    final File profDir = wspWinProject.getProfDir();

    final File strFile = new File(profDir, m_bean.getFileName());

    final BufferedWriter pw = new BufferedWriter(new FileWriter(strFile));

    /* Header *///  w ww.  j  a v a  2s .c o m
    final ZustandBean bean = getBean();
    final String waterName = ProfileBean.shortenName(bean.getWaterName(), ProfileBean.MAX_WATERNAME_LENGTH);
    final String name = ProfileBean.shortenName(bean.getName(), ProfileBean.MAX_STATENAME_LENGTH);
    pw.append(String.format("%d %d %s %s%n", m_profileBeans.size(), m_segmentBeans.size(), waterName, name)); //$NON-NLS-1$

    /* Profiles */
    for (final ProfileBean profile : m_profileBeans)
        pw.append(profile.formatStrLine()).append(SystemUtils.LINE_SEPARATOR);

    pw.append(SystemUtils.LINE_SEPARATOR);

    /* Segments */
    for (final ZustandSegmentBean segment : m_segmentBeans)
        pw.append(segment.formatLine()).append(SystemUtils.LINE_SEPARATOR);

    pw.close();
}

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

private int printWebRoleContent(BufferedWriter out, Role role, int counter, boolean includeForwarder) {

    try {/*from   www.  j  av a2  s .c  o m*/
        Policy p = (Policy) role.getResources().get("provisionPolicy");

        out.append("<WebRole name=\"" + role.getId() + "\"  vmsize=\"" + p.getSize() + "\" >");

        List<String> epList = printEndpoints(out, role);
        printLocalResources(out, role);
        printCertificates(out, role);
        printStartupTasks(out, role);
        printImports(out, role, includeForwarder);
        printSettings(out, role, includeForwarder);

        String staticDir = "";
        // Is this the rootContext application?
        for (String id : role.getChildren().keySet()) {
            Service srv = (Service) role.getChildren().get(id);

            if (srv.getProps().get("rootContext") != null
                    && srv.getProps().get("rootContext").equalsIgnoreCase("/")) {
                // Files staticContent=(Files)
                // s.getResources().get("appPackage");
                String fullQuery = srv.getProps().get("package");
                String nameQuery = ResourceLoader.getResourceName(fullQuery);
                String pathQuery = ResourceLoader.getResourcePath(fullQuery);
                Files staticContent = (Files) srv.getResources().get(nameQuery);
                staticDir = ArtifactManager.generateDeployPath(staticContent.getLocalPath(), true, pathQuery);
            }
        }

        if (StringUtils.empty(staticDir)) {
            // create a default empty directory
        }

        if (!StringUtils.empty(staticDir)) {
            try {

                out.append("<Sites>");
                out.append("<Site name=\"" + role.getId() + "\" physicalDirectory=\"" + staticDir + "\">");
                for (String key : role.getChildren().keySet()) {

                    Service service = null;
                    if (role.getChildren().get(key) instanceof Service) {
                        service = (Service) role.getChildren().get(key);
                    }

                    if (service != null) {
                        if (service.getProps().get("type") != null) {
                            if (service.getProps().get("type").equalsIgnoreCase("application")
                                    && !service.getProps().get("rootContext").equalsIgnoreCase("/")) {

                                String fQuery = service.getProps().get("package");
                                String nQuery = ResourceLoader.getResourceName(fQuery);
                                String pQuery = ResourceLoader.getResourcePath(fQuery);
                                Files appContent = (Files) service.getResources().get(nQuery);
                                String serviceArtifactDir = ArtifactManager
                                        .generateDeployPath(appContent.getLocalPath(), true, pQuery);
                                String rootContext = service.getProps().get("rootContext");

                                if (!StringUtils.empty(rootContext, serviceArtifactDir)) {
                                    out.append("<VirtualApplication name=\"" + rootContext
                                            + "\" physicalDirectory=\"" + serviceArtifactDir + "\" />");
                                } else {
                                    throw new RuntimeException("Web application " + service.getId()
                                            + " must contain app.rootContext property and physicalDirectory cannot be null.");
                                }
                            }
                        }
                    }

                }

                // print bindings
                out.append("<Bindings>");
                if (epList != null && !epList.isEmpty()) {
                    for (String id : epList) {
                        out.append("<Binding name=\"" + id + "\" endpointName=\"" + id + "\" />");
                    }
                }
                out.append("</Bindings>");
                out.append("</Site>");
                out.append("</Sites>");
                out.append("</WebRole>");

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return counter;
}