Example usage for org.apache.commons.io FileUtils readLines

List of usage examples for org.apache.commons.io FileUtils readLines

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils readLines.

Prototype

public static List readLines(File file) throws IOException 

Source Link

Document

Reads the contents of a file line by line to a List of Strings using the default encoding for the VM.

Usage

From source file:EntityToD2RHelpers.java

public EntityToD2RHelpers(String uri, String config_file, List<String> people, List<String> places,
        PrintWriter out) throws Exception {
    // In this example, I am assuming that the D2R server is running on localhost:2020
    //out.println("PREFIX vocab: <http://localhost:2020/vocab/resource/>");
    List<String> lines = (List<String>) FileUtils.readLines(new File(config_file));
    String d2r_host_and_port = lines.remove(0);
    String[] info = d2r_host_and_port.split(" ");
    System.out.println("D2R host = |" + info[0] + "| and port = |" + info[1] + "|");
    for (String line : lines) {
        Scanner scanner = new Scanner(line);
        scanner.useDelimiter(" ");
        String d2r_type = scanner.next();
        System.out.println("* d2r_type = " + d2r_type);
        while (scanner.hasNext()) {
            String term = scanner.next();
            String[] property_and_entity_type = term.split("/");
            System.out.println("   property: " + property_and_entity_type[0] + " entity type: "
                    + property_and_entity_type[1]);

            if (property_and_entity_type[1].equals("person")) {
                for (String person : people) {
                    // perform SPARQL queries to D2R server:
                    String sparql = "PREFIX vocab: <http://localhost:2020/vocab/resource/>\n"
                            + "SELECT ?subject ?name WHERE {\n" + "     ?subject " + property_and_entity_type[0]
                            + " ?name \n" + " FILTER regex(?name, \"" + person + "\") .\n" + "}\n"
                            + "LIMIT 10\n";
                    SparqlClient test = new SparqlClient("http://localhost:2020/sparql", sparql);
                    for (Map<String, String> bindings : test.variableBindings()) {
                        System.out.print("D2R result:" + bindings);
                        if (bindings.keySet().size() > 0) {
                            String blank_node = blankNodeURI("person");
                            out.println(blank_node + " <http://knowledgebooks.com/rdf/personName> \""
                                    + person.replaceAll("\"", "'") + "\" .");
                            out.println("<" + uri + "> <http://knowledgebooks.com/rdf/containsPerson> "
                                    + blank_node + " .");
                            out.println(blank_node + " <http://knowledgebooks.com/rdf/d2r_uri> \""
                                    + bindings.get("subject") + "\" .");
                        }//from  w w  w.ja v  a  2 s.co m
                    }
                }
            } else if (property_and_entity_type[1].equals("place")) {
                for (String place : places) {
                    // perform SPARQL queries to D2R server:
                    String sparql = "PREFIX vocab: <http://localhost:2020/vocab/resource/>\n"
                            + "SELECT ?subject ?name WHERE {\n" + "     ?subject " + property_and_entity_type[0]
                            + " ?name \n" + " FILTER regex(?name, \"" + place + "\") .\n" + "}\n"
                            + "LIMIT 10\n";
                    SparqlClient test = new SparqlClient("http://localhost:2020/sparql", sparql);
                    for (Map<String, String> bindings : test.variableBindings()) {
                        System.out.print("D2R result:" + bindings);
                        if (bindings.keySet().size() > 0) {
                            String blank_node = blankNodeURI("place");
                            out.println(blank_node + " <http://knowledgebooks.com/rdf/placeName> \""
                                    + place.replaceAll("\"", "'") + "\" .");
                            out.println("<" + uri + "> <http://knowledgebooks.com/rdf/containsPlace> "
                                    + blank_node + " .");
                            out.println(blank_node + " <http://knowledgebooks.com/rdf/d2r_uri> \""
                                    + bindings.get("subject") + "\" .");
                        }
                    }
                }
            }
        }
    }
    out.close();
}

From source file:com.daphne.es.maintain.icon.web.controller.tmp.GenCssSql.java

private static void readClass() throws IOException {
    String fromFile = "C:\\Documents and Settings\\Administrator\\?\\a.txt";
    String toFile = "C:\\Documents and Settings\\Administrator\\?\\b.sql";
    String template = "insert into `maintain_icon` (`id`, `identity`, `css_class`, `type`) values(%1$d, '%2$s', '%2$s', 'css_class');;";

    List<String> cssClassList = FileUtils.readLines(new File(fromFile));
    List<String> hasReadList = Lists.newArrayList();
    FileWriter writer = new FileWriter(toFile);

    for (int i = 0, l = cssClassList.size(); i < l; i++) {
        if (!hasReadList.contains(cssClassList.get(i))) {
            writer.write(String.format(template, i + 1, cssClassList.get(i).trim()));
            writer.write("\r\n");
            hasReadList.add(cssClassList.get(i));
        }//  w ww. j  ava  2s .  c o  m
    }

    writer.close();
}

From source file:KnowledgeBooksNlpGenerateRdfPropertiesFromWebPages.java

public KnowledgeBooksNlpGenerateRdfPropertiesFromWebPages(String config_file_path, PrintWriter out)
        throws IOException {
    this.out = out;
    extractNames = new ExtractNames();
    autoTagger = new AutoTagger();
    List<String> lines = (List<String>) FileUtils.readLines(new File(config_file_path));
    for (String line : lines) {
        Scanner scanner = new Scanner(line);
        scanner.useDelimiter(" ");
        try {/*from  w  w w  . ja v a 2 s.c  o  m*/
            String starting_url = scanner.next();
            int spider_depth = Integer.parseInt(scanner.next());
            spider(starting_url, spider_depth);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    this.out.close();
}

From source file:com.gargoylesoftware.htmlunit.javascript.regexp.mozilla.MozillaTestGenerator.java

/**
 * Outputs java test case for the specified JavaScript source.
 * @param author the author name// ww  w.  j ava 2  s  . c  om
 * @param htmlunitRoot HtmlUnit root path
 * @param mozillaRoot Mozilla root path
 * @param jsPath relative JavaScript source path, e.g. "/js/src/tests/js1_2/regexp/everything.js"
 * @param initialScript whether another initial script is needed or not
 * @throws IOException if a reading error occurs
 */
public static void printMozillaTest(final String author, final String htmlunitRoot, final String mozillaRoot,
        final String jsPath, final boolean initialScript) throws IOException {
    for (final Object o : FileUtils.readLines(new File(htmlunitRoot, "LICENSE.txt"))) {
        System.out.println(o);
    }
    final String[] jsPathTokens = jsPath.split("/");
    System.out.println(
            "package com.gargoylesoftware.htmlunit.javascript.regexp.mozilla." + jsPathTokens[4] + ";");
    System.out.println();
    System.out.println("import org.junit.Test;");
    System.out.println("import org.junit.runner.RunWith;");
    System.out.println();
    System.out.println("import com.gargoylesoftware.htmlunit.BrowserRunner;");
    System.out.println("import com.gargoylesoftware.htmlunit.WebDriverTestCase;");
    System.out.println("import com.gargoylesoftware.htmlunit.BrowserRunner.Alerts;");
    System.out.println();
    System.out.println("/**");
    System.out.println(" * Tests originally in '" + jsPath + "'.");
    System.out.println(" *");
    System.out.println(" * @author " + author);
    System.out.println(" */");
    System.out.println("@RunWith(BrowserRunner.class)");
    String className = jsPathTokens[jsPathTokens.length - 1];
    className = Character.toUpperCase(className.charAt(0)) + className.substring(1, className.length() - 3);
    System.out.println("public class " + className + "Test extends WebDriverTestCase {");
    final List<String> lines = FileUtils.readLines(new File(mozillaRoot, jsPath));
    int testNumber = 1;
    for (int i = 0; i < lines.size(); i++) {
        final String line = lines.get(i);
        if (line.startsWith("new TestCase")) {
            if (line.endsWith(";")) {
                System.out.println("ERROR...... test case ends with ; in " + (i + 1));
                continue;
            }
            int x = i + 1;
            String next = lines.get(x++).trim();
            while (!next.endsWith(";")) {
                next = lines.get(x++).trim();
            }
            final String expected = getExpected(next);
            final String script;
            if (next.startsWith("String(")) {
                final int p0 = next.indexOf("String(", 1) + "String(".length();
                script = next.substring(p0, next.length() - 3);
            } else if (next.startsWith("\"")) {
                script = next.substring(expected.length() + 3, next.length() - 2).trim();
            } else {
                script = next.substring(next.indexOf(',') + 1, next.length() - 2).trim();
            }
            System.out.println();
            System.out.println("    /**");
            System.out.println("     * Tests " + script + ".");
            System.out.println("     * @throws Exception if the test fails");
            System.out.println("     */");
            System.out.println("    @Test");
            System.out.println("    @Alerts(\"" + expected + "\")");
            System.out.println("    public void test" + testNumber++ + "() throws Exception {");
            if (initialScript) {
                System.out.print("        test(initialScript, ");
            } else {
                System.out.print("        test(");
            }
            System.out.println("\"" + script.replace("\\", "\\\\").replace("\"", "\\\"") + "\");");
            System.out.println("    }");
        }
    }
    System.out.println();
    if (initialScript) {
        System.out.println("    private void test(final String script) throws Exception {");
        System.out.println("        test(null, script);");
        System.out.println("    }");
        System.out.println("");
        System.out.println(
                "    private void test(final String initialScript, final String script) throws Exception {");
        System.out.println("        String html = \"<html><head><title>foo</title><script>\\n\";");
        System.out.println("        if (initialScript != null) {");
        System.out.println("            html += initialScript + \";\\n\";");
        System.out.println("        }");
        System.out.println("        html += \"  alert(\" + script + \");\\n\"");
        System.out.println("            + \"</script></head><body>\\n\"");
        System.out.println("            + \"</body></html>\";");
        System.out.println("        loadPageWithAlerts2(html);");
        System.out.println("    }");
    } else {
        System.out.println("    private void test(final String script) throws Exception {");
        System.out.println("        final String html = \"<html><head><title>foo</title><script>\\n\"");
        System.out.println("            + \"  alert(\" + script + \");\\n\"");
        System.out.println("            + \"</script></head><body>\\n\"");
        System.out.println("            + \"</body></html>\";");
        System.out.println("        loadPageWithAlerts2(html);");
        System.out.println("    }");
    }
    System.out.println("}");
}

From source file:net.landora.video.filestate.DirectoryUUIDChecker.java

public static void setUUID(File directory, String uuid) {
    try {//from  ww w . j  av a  2s . c om
        File uuidFile = new File(directory, UUID_FILE);
        Set<String> uuids = new LinkedHashSet<String>();

        if (uuidFile.exists()) {
            uuids.addAll(FileUtils.readLines(uuidFile));
        }
        uuids.add(uuid);
        FileUtils.writeLines(uuidFile, uuids);
    } catch (Exception e) {
        log.error("Error adding directory uuid: " + directory, e);

    }
}

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

@SuppressWarnings("unchecked")
public static void shuffler(String pairsFilename) throws IOException {
    List<String> fileWithPairs = FileUtils.readLines(new File(pairsFilename));
    Collections.shuffle(fileWithPairs);
    String outputFilename = pairsFilename.split("\\.")[0] + "_s.txt"; //output filename derived from the pairs filename
    FileUtils.writeLines(new File(outputFilename), fileWithPairs);
}

From source file:de.tudarmstadt.ukp.dkpro.tc.ml.modelpersist.ModelPersistUtil.java

public static List<String> initFeatureExtractors(File tcModelLocation) throws Exception {
    List<String> featureExtractors = new ArrayList<>();
    File featureExtractorsDescription = new File(tcModelLocation, MODEL_FEATURE_EXTRACTORS);
    List<String> featureConfiguration = FileUtils.readLines(featureExtractorsDescription);
    for (String featureExtractor : featureConfiguration) {
        featureExtractors.add(featureExtractor);
    }//from w w w  . ja va  2s. c o m
    return featureExtractors;
}

From source file:com.xiaomi.linden.lucene.similarity.IDFManager.java

private IDFManager(String fileName) throws IOException {
    List<String> lines = FileUtils.readLines(new File(fileName));
    wordsIDF = new HashMap<>();
    for (String line : lines) {
        String[] tokens = line.split("\t");
        if (tokens.length != 2) {
            continue;
        }/*from  w w  w  . j a v  a  2 s  .c  o  m*/
        Float idf = Float.valueOf(tokens[1]);
        if (idf > maxIDF) {
            maxIDF = idf;
        }
        wordsIDF.put(tokens[0], idf);
    }
}

From source file:codeKata04.DataImporter.java

/**
 * Imports data into the targetlist//  w w  w.  ja  v  a 2  s . c  o  m
 * @param file the file holding the data
 * @param targetList the target list of the import
 * @param factory the factory with the information of init parameters and creating new instances
 */
void importDataToList(File file, List<ImportableData> targetList, ImportableDataFactory factory) {
    try {

        List<String> lines = FileUtils.readLines(file);
        Pattern pattern = Pattern.compile(factory.getRegex());
        Matcher matcher;

        List<ImportableDataParameter> initParameters = factory.getInitParameters();

        for (String line : lines) {
            matcher = pattern.matcher(line);
            if (matcher.find()) {

                for (ImportableDataParameter initParameter : initParameters) {
                    initParameter.setValue(matcher.group(initParameter.getIdx()));
                }

                ImportableData instance = factory.createInstance(initParameters);
                targetList.add(instance);

            }
        }

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

From source file:com.l2jfree.tools.NewLineChecker.java

private static void parse(File f) throws IOException {
    if (f.isDirectory()) {
        for (File f2 : f.listFiles(FILTER))
            parse(f2);//from w w w. j  a v a  2 s  .  c o  m
        return;
    }

    final String input = FileUtils.readFileToString(f);
    final List<String> inputLines = FileUtils.readLines(f);

    final int r = StringUtils.countMatches(input, "\r");
    final int n = StringUtils.countMatches(input, "\n");
    final int rn = StringUtils.countMatches(input, "\r\n");

    final char lastChar = input.charAt(input.length() - 1);
    boolean missingNewline = false;

    if (lastChar != '\r' && lastChar != '\n') {
        System.out.println("--- " + f.getCanonicalPath());
        System.out.println(lastChar);

        MISSING_NEWLINE++;

        missingNewline = true;
    }

    // fully "\r\n"
    if (r == n && r == rn && n == rn) {
        RN++;
        if (missingNewline)
            FileUtils.writeLines(f, inputLines, "\r\n");
        return;
    }

    // fully "\n"
    if (r == 0 && rn == 0) {
        N++;
        System.out.println("n " + f.getName());
        if (missingNewline)
            FileUtils.writeLines(f, inputLines, "\n");
        return;
    }

    System.out.println("--- " + f.getCanonicalPath());
    System.out.println("r: " + r);
    System.out.println("n: " + n);
    System.out.println("rn: " + rn);

    FileUtils.writeLines(f, inputLines, f.getName().endsWith(".sh") ? "\n" : "\r\n");

    // fully "\r"
    if (n == 0 && rn == 0) {
        R++;
        return;
    }

    // mixed
    MIXED++;
}