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.verigreen.collector.systemtest.SystemTestBase.java

protected void addNewFile(String filePath, String content) throws IOException {

    File newFileToAdd = new File(_localRepositoryFolder + "/" + filePath);
    newFileToAdd.getParentFile().mkdirs();
    BufferedWriter output = new BufferedWriter(new FileWriter(newFileToAdd, true));
    output.append(content);
    output.close();//from   w  w  w  .j a  va2s .  c o m
}

From source file:com.termmed.idcreation.IdCreation.java

/**
 * Execute.//from w  ww. ja va 2  s  .c o m
 *
 * @throws IOException Signals that an I/O exception has occurred.
 */
public void execute() throws IOException {

    IdAssignmentBI idAssignment = new IdAssignmentImpl(endPointURL, username, pass);

    File relFile = new File(componentFile);
    File newRelFile = new File(relFile.getParent(), "uuids_" + relFile.getName());
    FileInputStream rfis = new FileInputStream(componentFile);
    InputStreamReader risr = new InputStreamReader(rfis, "UTF-8");
    BufferedReader rbr = new BufferedReader(risr);
    String header = rbr.readLine();

    FileOutputStream fos = new FileOutputStream(newRelFile);
    OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
    BufferedWriter bw = new BufferedWriter(osw);
    bw.append(header);
    bw.append("\r\n");

    String line;
    String[] spl;
    int i;
    UUID uuid;
    List<UUID> list = new ArrayList<UUID>();
    while ((line = rbr.readLine()) != null) {
        spl = line.split("\t", -1);
        Long sctid = null;
        try {
            sctid = Long.parseLong(spl[0]);
            bw.append(line);
            bw.append("\r\n");
        } catch (Exception e) {
            try {
                uuid = UUID.fromString(spl[0]);
            } catch (Exception e2) {
                uuid = UUID.randomUUID();
            }

            list.add(uuid);
            bw.append(uuid.toString());
            bw.append("\t");
            for (i = 1; i < spl.length; i++) {
                bw.append(spl[i]);
                if (i == spl.length - 1) {
                    bw.append("\r\n");
                } else {
                    bw.append("\t");
                }
            }
        }
    }
    bw.close();
    bw = null;
    rbr.close();
    rbr = null;
    HashMap<UUID, Long> sctIdMap = new HashMap<UUID, Long>();
    String sPart = ("0" + String.valueOf(partitionId)).substring(0, 2);
    try {
        sctIdMap = idAssignment.createSCTIDList(list, namespaceId, sPart, releaseDate, releaseDate,
                releaseDate);
    } catch (Exception cE) {
        log.error("Message : SCTID creation error for list ", cE);
    }
    File finalRelFile = new File(relFile.getParent(), "tmp_" + relFile.getName());
    rfis = new FileInputStream(newRelFile);
    risr = new InputStreamReader(rfis, "UTF-8");
    rbr = new BufferedReader(risr);
    header = rbr.readLine();

    fos = new FileOutputStream(finalRelFile);
    osw = new OutputStreamWriter(fos, "UTF-8");
    bw = new BufferedWriter(osw);
    bw.append(header);
    bw.append("\r\n");

    while ((line = rbr.readLine()) != null) {
        spl = line.split("\t", -1);
        if (spl[0].contains("-")) {
            uuid = UUID.fromString(spl[0]);
            Long id = sctIdMap.get(uuid);
            if (id != null) {
                bw.append(id.toString());
                bw.append("\t");
                for (i = 1; i < spl.length; i++) {
                    bw.append(spl[i]);
                    if (i == spl.length - 1) {
                        bw.append("\r\n");
                    } else {
                        bw.append("\t");
                    }
                }
            } else {
                bw.append(line);
                bw.append("\r\n");

            }
        } else {
            bw.append(line);
            bw.append("\r\n");

        }
    }
    bw.close();
    bw = null;
    rbr.close();
    rbr = null;

    if (newRelFile.exists()) {
        newRelFile.delete();
    }
    if (relFile.exists()) {
        String inputFile = relFile.getAbsolutePath();
        File reconFile = new File(relFile.getParent(), "Reconcil_" + relFile.getName());
        relFile.renameTo(reconFile);
        File outFile = new File(inputFile);
        finalRelFile.renameTo(outFile);

    }

}

From source file:org.zgif.model.tools.GenerationPostProcessor.java

public void rewriteFile(File sourceFile, String packageName) throws Throwable {
    final String fileName = sourceFile.getName();
    final String currentModelClassName = fileName.substring(0, fileName.length() - 5);

    Set<String> usedModelClasses = new HashSet<String>();

    final String linePublicClass = "public class " + currentModelClassName + " {";
    String classExtension = null;
    if (packageName.equals(NODE_PACKAGE)) {
        classExtension = "AbstractNode";
        usedModelClasses.add("AbstractNode");
    } else if (packageName.equals(ENTITY_PACKAGE)) {
        classExtension = "AbstractEntityNode";
        usedModelClasses.add("AbstractEntityNode");
    } else if (packageName.equals(GROUP_PACKAGE)) {
        classExtension = "AbstractGroupNode";
        usedModelClasses.add("AbstractGroupNode");
    }//from   ww  w  . j a  v  a 2s .  com

    // backup File
    File tmpFile = new File(sourceFile.getParent(), fileName + ".bak");
    sourceFile.renameTo(tmpFile);

    // read file
    BufferedReader reader = new BufferedReader(new FileReader(tmpFile));

    StringBuilder body = new StringBuilder((int) tmpFile.length());
    String lineBefore = "";
    Set<String> flags = new HashSet<String>();
    for (String line = reader.readLine(); line != null; line = reader.readLine()) {
        if (lineBefore.equals("    /**") && line.contains("extensionMap")) {
            flags.add("xetter_extensionMap");
            body.append("*/");
            body.append(System.lineSeparator());
        }
        if (lineBefore.equals("    /**") && line.contains("validFrom")) {
            flags.add("xetter_validFrom");
            body.append("*/");
            body.append(System.lineSeparator());
        }
        if (lineBefore.equals("    /**") && line.contains("validTo")) {
            flags.add("xetter_validTo");
            body.append("*/");
            body.append(System.lineSeparator());
        }

        if (!removeLines.contains(line) && !flags.contains("xetter_extensionMap")
                && !flags.contains("xetter_validFrom") && !flags.contains("xetter_validTo")) {
            for (String modelClass : classPackageMap.keySet()) {
                if (!modelClass.equals(currentModelClassName) && (line.contains(" " + modelClass + " ")
                        || line.contains(modelClass + ".class") || line.contains("extends " + modelClass))) {
                    usedModelClasses.add(modelClass);
                }
            }

            if (classExtension != null && !flags.contains("PublicClassPassed")
                    && line.equals(linePublicClass)) {
                line = line.substring(0, line.length() - 1) + "extends " + classExtension + " {";
                flags.add("PublicClassPassed");
            }

            if (!line.startsWith("package")) {
                body.append(line);
                body.append(System.lineSeparator());
            }
        }

        if (flags.contains("xetter_extensionMap") && line.equals("    }")) {
            flags.remove("xetter_extensionMap");
        }
        if (flags.contains("xetter_validFrom") && line.equals("    }")) {
            flags.remove("xetter_validFrom");
        }
        if (flags.contains("xetter_validTo") && line.equals("    }")) {
            flags.remove("xetter_validTo");
        }

        lineBefore = line;
    }
    reader.close();

    // append package and imports
    BufferedWriter writer = new BufferedWriter(new FileWriter(sourceFile));
    writer.append("package " + packageName + ";" + System.lineSeparator() + System.lineSeparator());
    for (String usedModel : usedModelClasses) {
        writer.append(
                "import " + classPackageMap.get(usedModel) + "." + usedModel + ";" + System.lineSeparator());
    }

    // write body
    writer.append(body.toString());
    writer.close();

    // delete original file
    tmpFile.delete();
}

From source file:vt.diamond.LayoutChangesActivity.java

private void addItem(String question, boolean write) throws IOException {
    findViewById(android.R.id.empty).setVisibility(View.GONE);
    // Instantiate a new "row" view.
    final ViewGroup newView = (ViewGroup) LayoutInflater.from(this).inflate(R.layout.list_item_example,
            mContainerView, false);/*from  www .  ja  v  a  2s  .c  o  m*/

    // Set the text in the new row to a random country.
    ((TextView) newView.findViewById(android.R.id.text1)).setText(question);

    if (write) {
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(openFileOutput("usrQues.txt", Context.MODE_APPEND)));
        writer.append(question);
        writer.newLine();
        writer.flush();
        writer.close();
    }
    // Set a click listener for the "X" button in the row that will remove the row.
    newView.findViewById(R.id.delete_button).setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

            //remove question from local stoarage
            String removeString = ((TextView) newView.findViewById(android.R.id.text1)).getText().toString();

            BufferedReader myQues = null;
            String nextln = null;
            try {
                myQues = new BufferedReader(new InputStreamReader(openFileInput("usrQues.txt")));
                nextln = myQues.readLine();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            //buffer to hold new contents of the file
            StringBuffer contents = new StringBuffer();

            //copy file
            while (nextln != null) {

                if (!removeString.equals(nextln)) {
                    contents.append(nextln + "\n");
                }
                try {
                    nextln = myQues.readLine();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            //rewrite the file
            BufferedWriter myQuesNew = null;
            try {
                myQuesNew = new BufferedWriter(
                        new OutputStreamWriter(openFileOutput("usrQues.txt", Context.MODE_PRIVATE)));
                myQuesNew.write(contents.toString());
                myQuesNew.flush();
                myQuesNew.close();
                myQues.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            // Remove the row from its parent (the container view).
            // Because mContainerView has android:animateLayoutChanges set to true,
            // this removal is automatically animated.
            mContainerView.removeView(newView);

            // If there are no rows remaining, show the empty view.
            if (mContainerView.getChildCount() == 0) {
                findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
            }
        }
    });

    // Because mContainerView has android:animateLayoutChanges set to true,
    // adding this view is automatically animated.
    mContainerView.addView(newView, 0);
}

From source file:org.jamwiki.migrate.MediaWikiXmlExporter.java

/**
 *
 *///from   w w w .  j  a  v a2s  .  c  o m
public void exportToFile(File file, String virtualWiki, List<String> topicNames, boolean excludeHistory)
        throws MigrationException {
    OutputStreamWriter fileWriter = null;
    BufferedWriter bufferedWriter = null;
    boolean success = false;
    try {
        fileWriter = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.append(
                "<mediawiki xmlns=\"http://www.mediawiki.org/xml/export-0.7/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.mediawiki.org/xml/export-0.7/ http://www.mediawiki.org/xml/export-0.7.xsd\" version=\"0.7\" xml:lang=\"en\">");
        this.writeSiteInfo(bufferedWriter, virtualWiki);
        this.writePages(bufferedWriter, virtualWiki, topicNames, excludeHistory);
        bufferedWriter.append("\n</mediawiki>");
        success = true;
    } catch (DataAccessException e) {
        throw new MigrationException(e);
    } catch (IOException e) {
        throw new MigrationException(e);
    } finally {
        IOUtils.closeQuietly(bufferedWriter);
        IOUtils.closeQuietly(fileWriter);
        if (!success) {
            // make sure partial files are deleted
            file.delete();
        }
    }
}

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

private void printLocalResources(BufferedWriter out, Role r) {
    try {//from  w ww  .ja  va 2 s.c o m
        out.append("<LocalResources>");
        out.append(
                "<LocalStorage name=\"localInstallDirectory\" cleanOnRoleRecycle=\"true\" sizeInMB=\"4096\" />");
        for (String key : r.getResources().keySet()) {
            Resource res = r.getResources().get(key);
            if (res instanceof AzureLocalStorage) {
                AzureLocalStorage ls = (AzureLocalStorage) res;
                out.append("<LocalStorage name=\"" + ls.getName() + "\" cleanOnRoleRecycle=\""
                        + ls.getCleanOnRecycle() + "\" sizeInMB=\"" + ls.getSizeInMB() + "\" />");
            }
        }
        out.append("</LocalResources>");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.verigreen.collector.systemtest.SystemTestBase.java

/**
 * @param destinationFolderForNewFile/*from  w w  w . j ava 2s.  c  o m*/
 * @param newFileName
 * @throws IOException
 */
protected void appendToFile(String pathToFile, String content) throws IOException {
    BufferedWriter outputCommiter3 = new BufferedWriter(new FileWriter(pathToFile, true));
    outputCommiter3.newLine();
    outputCommiter3.append(content);
    outputCommiter3.close();
}

From source file:uk.ac.ebi.arrayexpress.servlets.HttpProxyServlet.java

@Override
protected void doRequest(HttpServletRequest request, HttpServletResponse response, RequestType requestType)
        throws ServletException, IOException {
    RegexHelper MATCH_URL_REGEX = new RegexHelper("/+(.+)", "i");
    RegexHelper TEST_HOST_IN_URL_REGEX = new RegexHelper("^http\\:/{2}([^/]+)/", "i");
    RegexHelper SQUARE_BRACKETS_REGEX = new RegexHelper("\\[\\]", "g");

    logRequest(logger, request, requestType);

    String url = MATCH_URL_REGEX.matchFirst(request.getPathInfo());
    url = url.replaceFirst("http:/{1,2}", "http://"); // stupid hack as tomcat 6.0 removes second forward slash
    String queryString = request.getQueryString();

    if (0 < url.length()) {
        if (!TEST_HOST_IN_URL_REGEX.test(url)) { // no host here, will self
            url = "http://localhost:" + String.valueOf(request.getLocalPort()) + "/" + url;
        }//  ww w .j av a  2s .  c  o m
        logger.debug("Will access [{}]", url);

        GetMethod getMethod = new GetMethod(url);

        if (null != queryString) {
            queryString = SQUARE_BRACKETS_REGEX.replace(queryString, "%5B%5D");
            getMethod.setQueryString(queryString);
        }

        Enumeration requestHeaders = request.getHeaderNames();
        while (requestHeaders.hasMoreElements()) {
            String name = (String) requestHeaders.nextElement();
            String value = request.getHeader(name);
            if (null != value) {
                getMethod.setRequestHeader(name, value);
            }
        }

        try {
            httpClient.executeMethod(getMethod);

            int statusCode = getMethod.getStatusCode();
            long contentLength = getMethod.getResponseContentLength();
            logger.debug("Got response [{}], length [{}]", statusCode, contentLength);

            Header[] responseHeaders = getMethod.getResponseHeaders();
            for (Header responseHeader : responseHeaders) {
                String name = responseHeader.getName();
                String value = responseHeader.getValue();
                if (null != name && null != value && !(name.equals("Server") || name.equals("Date")
                        || name.equals("Transfer-Encoding"))) {
                    response.setHeader(responseHeader.getName(), responseHeader.getValue());
                }
            }

            if (200 != statusCode) {
                response.setStatus(statusCode);
            }

            InputStream inStream = getMethod.getResponseBodyAsStream();
            if (null != inStream) {
                BufferedReader in = new BufferedReader(new InputStreamReader(inStream));

                BufferedWriter out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream()));

                CharBuffer buffer = CharBuffer.allocate(PROXY_BUFFER_SIZE);
                while (in.read(buffer) >= 0) {
                    buffer.flip();
                    out.append(buffer);
                    buffer.clear();
                }

                in.close();
                out.close();
            }
        } catch (Exception x) {
            if (x.getClass().getName().equals("org.apache.catalina.connector.ClientAbortException")) {
                logger.warn("Client aborted connection");
            } else {
                logger.error("Caught an exception:", x);
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, x.getMessage());
            }
        } finally {
            getMethod.releaseConnection();
        }
    }
}

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

private void printGlobalSettings(BufferedWriter out, Role r, boolean enableForwarder) {
    try {/*from  ww w  .  j av a  2s  .  com*/
        out.append("<Setting name=\"deploy.storage\" />");
        for (String p : r.getProps().keySet()) {
            out.append("<Setting name=\"" + p + "\" />");
        }

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

From source file:com.zestedesavoir.zestwriter.model.Content.java

public void saveToHtml(File file, MdTextController index) {
    try (FileOutputStream fos = new FileOutputStream(file)) {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos, "UTF8"));
        String mdValue = exportContentToMarkdown(0, getDepth());
        String htmlValue = StringEscapeUtils.unescapeHtml4(index.markdownToHtml(mdValue));
        htmlValue = normalizeHtml(htmlValue);
        writer.append(MainApp.getMdUtils().addHeaderAndFooterStrict(htmlValue, getTitle()));
        writer.flush();/*from w ww  .  j  a v  a2 s.  co m*/
    } catch (Exception e) {
        MainApp.getLogger().error(e.getMessage(), e);
    }
}