Example usage for org.apache.commons.io IOUtils writeLines

List of usage examples for org.apache.commons.io IOUtils writeLines

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils writeLines.

Prototype

public static void writeLines(Collection lines, String lineEnding, OutputStream output, String encoding)
        throws IOException 

Source Link

Document

Writes the toString() value of each item in a collection to an OutputStream line by line, using the specified character encoding and the specified line ending.

Usage

From source file:de.tudarmstadt.ukp.csniper.resbuild.stuff.InclusionsCreator.java

@Test
public void createInclusionsFile() throws IOException {
    List<String> all = read(BASE_0, "xml");
    //      all.removeAll(cut(read(BASE, "csv"), read(BASE, "xz")));
    all.removeAll(cut(read(BASE, "csv"), stripPlusXml(read("serialized.txt"))));
    //      all.removeAll(read(BASE, "csv"));
    FileUtils.writeLines(new File(BASE, "inclusions.txt"), "UTF-8", all);
    //      all.removeAll(read(BASE, "xz"));
    //      all.removeAll(read(BASE, "csv"));
    IOUtils.writeLines(all, "\n", System.out, "UTF-8");
}

From source file:com.dangdang.config.service.web.mb.PropertyExportManagedBean.java

/**
 * ???properties//  w  w  w  . j  a  v  a2  s .co  m
 * 
 * @param groupName
 * @return
 */
public StreamedContent generateFile(String groupName) {
    LOGGER.info("Export config group: {}", groupName);

    StreamedContent file = null;
    if (!Strings.isNullOrEmpty(groupName)) {
        List<PropertyItemVO> items = nodeBusiness.findPropertyItems(nodeAuth.getAuthedNode(),
                versionMB.getSelectedVersion(), groupName);

        if (!items.isEmpty()) {
            ByteArrayOutputStream out = null;
            try {
                out = new ByteArrayOutputStream();
                List<String> lines = formatPropertyLines(groupName, items);
                IOUtils.writeLines(lines, "\r\n", out, Charsets.UTF_8.displayName());
                InputStream in = new ByteArrayInputStream(out.toByteArray());

                String fileName = groupName + ".properties";
                file = new DefaultStreamedContent(in, "text/plain", fileName, Charsets.UTF_8.name());
            } catch (IOException e) {
                LOGGER.error(e.getMessage(), e);
            } finally {
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        // DO NOTHING
                    }
                }
            }
        }
    }
    return file;
}

From source file:com.dangdang.config.service.web.mb.PropertyExportManagedBean.java

/**
 * ??ZIP//  www . j  a  v  a  2s .c  o m
 * 
 * @return
 */
public StreamedContent generateFileAll() {
    LOGGER.info("Export all config group");
    StreamedContent file = null;

    String authedNode = ZKPaths.makePath(nodeAuth.getAuthedNode(), versionMB.getSelectedVersion());
    List<String> children = nodeService.listChildren(authedNode);
    if (children != null && !children.isEmpty()) {
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ZipOutputStream zipOutputStream = new ZipOutputStream(out);
            for (String groupName : children) {
                String groupPath = ZKPaths.makePath(authedNode, groupName);
                String fileName = ZKPaths.getNodeFromPath(groupPath) + ".properties";

                List<PropertyItemVO> items = nodeBusiness.findPropertyItems(nodeAuth.getAuthedNode(),
                        versionMB.getSelectedVersion(), groupName);
                List<String> lines = formatPropertyLines(groupName, items);
                if (!lines.isEmpty()) {
                    ZipEntry zipEntry = new ZipEntry(fileName);
                    zipOutputStream.putNextEntry(zipEntry);
                    IOUtils.writeLines(lines, "\r\n", zipOutputStream, Charsets.UTF_8.displayName());
                    zipOutputStream.closeEntry();
                }
            }

            zipOutputStream.close();
            byte[] data = out.toByteArray();
            InputStream in = new ByteArrayInputStream(data);

            String fileName = authedNode.replace('/', '-') + ".zip";
            file = new DefaultStreamedContent(in, "application/zip", fileName, Charsets.UTF_8.name());
        } catch (IOException e) {
            LOGGER.error(e.getMessage(), e);
        }
    }

    return file;
}

From source file:eu.annocultor.converters.time.OntologyToHtmlGenerator.java

String makeTermDefinitionFile(RepositoryConnection connection, ValueFactory factory, StringInStack url)
        throws RepositoryException, FileNotFoundException, IOException {
    List<String> term = new ArrayList<String>();
    term.add(/*from ww  w . j  a  va 2 s . c o m*/
            "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
    term.add("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">");
    term.add("<head>");
    term.add("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />");
    term.add("<link rel=\"stylesheet\" href=\"terms.css\" type=\"text/css\" />");

    List<String> pref = collectLabels(connection, factory, Concepts.SKOS.LABEL_PREFERRED.getUri(), url);
    List<String> alt = collectLabels(connection, factory, Concepts.SKOS.LABEL_ALT.getUri(), url);
    List<String> beginDate = collectLabels(connection, factory, Concepts.ANNOCULTOR.DATE_BEGIN.getUri(), url);
    List<String> endDate = collectLabels(connection, factory, Concepts.ANNOCULTOR.DATE_END.getUri(), url);

    String prefLabel = null;
    if (!pref.isEmpty()) {
        prefLabel = StringUtils.join(pref.toArray(), ", ");
    }
    if (prefLabel == null && !alt.isEmpty()) {
        prefLabel = alt.get(0);
    }
    if (prefLabel == null) {
        prefLabel = "Time";
    }
    term.add("<title>" + prefLabel + "</title>");
    term.add("</head>");
    term.add("<body>");
    term.add("<p><a href=\"http://annocultor.eu/\">Back to AnnoCultor</a></p>");

    formatLabels(term, pref, alt);
    formatDates(term, beginDate, endDate);

    term.add("</body>");
    term.add("</html>");

    FileOutputStream os = new FileOutputStream(
            new File(outputDir, StringUtils.substringAfterLast(url.getString(), "/")));
    IOUtils.writeLines(term, "\n", os, "UTF-8");
    os.close();
    return prefLabel;
}

From source file:eu.annocultor.converters.time.OntologyToHtmlGenerator.java

@Override
public void saveListOfUrls(String fileWithSelection, Collection<String> passedUnSorted,
        List<String> passedSorted) throws IOException {

    for (Node child : tree.children) {
        printBranch(child, urls);// w  w w .  j av  a 2  s. c o m
    }
    urls.add("</ul>");
    urls.add("</div>");

    urls.add("<script type=\"text/javascript\">");
    urls.add("var tree1;");

    urls.add("(function() {");
    urls.add(" var treeInit = function() {");
    urls.add("  tree1 = new YAHOO.widget.TreeView(\"markup\");");
    urls.add("  tree1.render();    ");
    urls.add("  tree1.subscribe('dblClickEvent',tree1.onEventEditNode);");
    urls.add("  };");
    urls.add(" YAHOO.util.Event.onDOMReady(treeInit);");
    urls.add("})();");
    urls.add("</script>");

    urls.add("<div id=\"treeDiv2\" class=\"whitebg\"></div>");
    urls.add("</body>");
    urls.add("</html>");
    IOUtils.writeLines(urls, "\n", new FileOutputStream(new File(outputDir, "index.html")), "UTF-8");
}

From source file:com.example.util.FileUtils.java

/**
 * Writes the <code>toString()</code> value of each item in a collection to
 * the specified <code>File</code> line by line.
 * The specified character encoding and the line ending will be used.
 *
 * @param file  the file to write to/* w  ww. j  a  va2 s.co m*/
 * @param encoding  the encoding to use, {@code null} means platform default
 * @param lines  the lines to write, {@code null} entries produce blank lines
 * @param lineEnding  the line separator to use, {@code null} is system default
 * @param append if {@code true}, then the lines will be added to the
 * end of the file rather than overwriting
 * @throws IOException in case of an I/O error
 * @throws java.io.UnsupportedEncodingException if the encoding is not supported by the VM
 * @since 2.1
 */
public static void writeLines(File file, String encoding, Collection<?> lines, String lineEnding,
        boolean append) throws IOException {
    FileOutputStream out = null;
    try {
        out = openOutputStream(file, append);
        final BufferedOutputStream buffer = new BufferedOutputStream(out);
        IOUtils.writeLines(lines, lineEnding, buffer, encoding);
        buffer.flush();
        out.close(); // don't swallow close Exception if copy completes normally
    } finally {
        IOUtils.closeQuietly(out);
    }
}

From source file:org.apache.kylin.rest.util.ControllerSplitter.java

private static void chopOff(File f, String annoPtn) throws IOException {

    System.out.println("Processing " + f);

    FileInputStream is = new FileInputStream(f);
    List<String> lines = IOUtils.readLines(is, "UTF-8");
    is.close();/*  w  ww.j  a  va 2 s  .  co  m*/
    List<String> outLines = new ArrayList<>(lines.size());

    boolean del = false;
    for (String l : lines) {
        if (l.startsWith("    @") && l.contains(annoPtn))
            del = true;

        if (del)
            System.out.println("x " + l);
        else
            outLines.add(l);

        if (del && l.startsWith("    }"))
            del = false;
    }

    if (!dryRun && outLines.size() < lines.size()) {
        FileOutputStream os = new FileOutputStream(f);
        IOUtils.writeLines(outLines, "\n", os, "UTF-8");
        os.close();
        System.out.println("UPDATED " + f);
    } else {
        System.out.println("skipped");
    }

    System.out.println("============================================================================");
}

From source file:org.opensingular.form.io.IOUtil.java

public static void writeLines(OutputStream out, String... lines) throws IOException {
    IOUtils.writeLines(Arrays.asList(lines), IOUtils.LINE_SEPARATOR_UNIX, out, UTF8);
}

From source file:org.sonar.server.source.ws.RawAction.java

@Override
public void handle(Request request, Response response) {
    String fileKey = request.mandatoryParam("key");
    UserSession.get().checkComponentPermission(UserRole.CODEVIEWER, fileKey);
    DbSession session = dbClient.openSession(false);
    try {//  w  w  w.  j av a 2  s.c  om
        ComponentDto componentDto = dbClient.componentDao().getByKey(session, fileKey);
        List<String> lines = sourceService.getLinesAsTxt(componentDto.uuid(), null, null);
        response.stream().setMediaType("text/plain");
        IOUtils.writeLines(lines, "\n", response.stream().output(), Charsets.UTF_8);
    } catch (IOException e) {
        throw new IllegalStateException("Fail to write raw source of file " + fileKey, e);
    } finally {
        session.close();
    }
}

From source file:poisondog.demo.FileDemo.java

public static void main(String[] args) {
    try {//from   ww w  .j a  v a 2s . c om
        IData data = (IData) FileFactory.getFile("/home/poisondog/Downloads/temp.txt");
        HashSet<String> all = new HashSet<String>();
        for (String line : IOUtils.readLines(data.getInputStream(), "utf8")) {
            all.add(line);
        }
        IData to = (IData) FileFactory.getFile("/home/poisondog/Downloads/result.txt");
        IOUtils.writeLines(all, null, to.getOutputStream(), "utf8");
    } catch (Exception e) {
        e.printStackTrace();
    }
}