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

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

Introduction

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

Prototype

public static String readFileToString(File file, String encoding) throws IOException 

Source Link

Document

Reads the contents of a file into a String.

Usage

From source file:com.github.stagirs.common.model.DocumentParser.java

public static Document parse(File file) throws IOException {
    Document doc = new Document();
    doc.setId(file.getName());/*from   w w w .  java 2  s . c  o m*/
    Iterator<String> list = split(FileUtils.readFileToString(file, "utf-8")).iterator();
    while (list.hasNext()) {
        String item = list.next();
        if (item.equals("<div class='section'>")) {
            doc.getBlocks().add(parseSection(doc.getId(), item, list));
            continue;
        }
        if (item.startsWith("<p")) {
            doc.getBlocks().add(parsePoint(doc.getId(), item, list));
            continue;
        }
        if (item.startsWith("<div class='title' ")) {
            item = item.split("semantic='")[1];
            doc.setTitleSemantic(Double.parseDouble(item.substring(0, item.indexOf("'"))));
            doc.setTitle(list.next());
            list.next();
            continue;
        }
        if (item.equals("<div class='author'>")) {
            doc.setAuthor(list.next());
            list.next();
            continue;
        }
        if (item.equals("<div class='classifier'>")) {
            doc.setClassifier(list.next());
            list.next();
            continue;
        }
        if (item.equals("<div class='thanks'>")) {
            doc.setThanks(list.next());
            list.next();
            continue;
        }
        if (item.equals("<div class='output'>")) {
            doc.setOutput(list.next());
            list.next();
            continue;
        }
    }
    return doc;
}

From source file:mysynopsis.HTMLWriter.java

public static String writeHTML() throws IOException {

    JSONWriter.writeData();/*  www  .j av a  2 s.c o  m*/

    File htmlfile = null;
    try {

        htmlfile = new File("template.html");
        String htmlstr;
        htmlstr = FileUtils.readFileToString(htmlfile, "UTF-8");
        //    System.out.println(htmlstr);

        htmlstr = htmlstr.replace("$type", imgExtension);
        htmlstr = htmlstr.replace("$imgStr", imgString);
        htmlstr = htmlstr.replace("$title", name);
        htmlstr = htmlstr.replace("$name", name);

        if (initial.length() > 0) {
            htmlstr = htmlstr.replace("$initial", "[" + initial + "]");
        } else {
            htmlstr = htmlstr.replace("$initial", initial);
        }

        htmlstr = htmlstr.replace("$desig", designation);
        htmlstr = htmlstr.replace("$department", dept);
        htmlstr = htmlstr.replace("$university", university);
        htmlstr = htmlstr.replace("$officeroom", office);
        htmlstr = htmlstr.replace("$officehours", officehours);
        htmlstr = htmlstr.replace("$phone", phone);
        htmlstr = htmlstr.replace("$email", email);
        htmlstr = htmlstr.replace("$resume", resumelink);
        htmlstr = htmlstr.replace("$biograph", biog);
        htmlstr = htmlstr.replace("$educational", education);

        /*htmlstr = htmlstr.replace("$highschool", educ[0]);
        htmlstr = htmlstr.replace("$hsduration", educ[1]);
        htmlstr = htmlstr.replace("$college", educ[2]);
        htmlstr = htmlstr.replace("$clgduration", educ[3]);
        htmlstr = htmlstr.replace("$undergrad_degree", educ[4]);
        htmlstr = htmlstr.replace("$undergradvarsity", educ[5]);
        htmlstr = htmlstr.replace("$grad_degree", educ[6]);
        htmlstr = htmlstr.replace("$gradvarsity", educ[7]);*/
        htmlstr = htmlstr.replace("$professional", professional);
        //    System.out.println(professional);
        htmlstr = htmlstr.replace("$awards", awards);

        //      JOptionPane.showMessageDialog(null,educ[1]);

        File newhtml;
        try {
            newhtml = new File("index.html");
            FileUtils.writeStringToFile(newhtml, htmlstr, "UTF-8");
            return "HTML Export Successful!!";
        } catch (IOException | HeadlessException e) {

            return "An Error Occured. Please Restart the Application";

        }
    } catch (IOException e) {

        return "Template (template.html) File Not Found!";
    }

}

From source file:io.stallion.plugins.javascript.JsFileReader.java

public static String readToString(String file, String pluginFolder) {
    if (!file.startsWith(Settings.instance().getTargetFolder() + "/js")
            && !file.startsWith(Settings.instance().getTargetFolder() + "/plugins")) {
        throw new UsageException("You can cannot access the file " + file + " from this location");
    }/*from w w  w . ja v  a2 s  . c o  m*/
    if (!empty(pluginFolder)) {
        if (!file.startsWith(pluginFolder)) {
            throw new UsageException("File " + file + " is not in the javascript folder " + pluginFolder);
        }
    }
    if (!file.endsWith(".js")) {
        throw new UsageException("This is not a .js file: " + file);
    }
    try {
        return FileUtils.readFileToString(new File(file), "UTF-8");
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.mobius.software.mqtt.performance.runner.util.RequestFormatter.java

public static List<ScenarioRequest> parseScenarioRequests(File file)
        throws JsonParseException, JsonMappingException, IOException {
    return parseScenarioRequests(FileUtils.readFileToString(file, "UTF-8"));
}

From source file:com.taobao.datax.engine.conf.ParseXMLUtil.java

/**
 * Parse dataX job configuration file./*from   w  ww  . j a  va 2 s .  c om*/
 * 
 * @param filename
 *            Job configure filename.
 * 
 * @return a JobConf instance which describes this Job configuration file.
 * 
 * */
@SuppressWarnings("unchecked")
public static JobConf loadJobConfig(String filename) {
    JobConf job = new JobConf();
    Document document;
    try {
        String xml = FileUtils.readFileToString(new File(filename), "UTF-8");
        document = DocumentHelper.parseText(xml);
    } catch (DocumentException e) {
        LOG.error("DataX Can not find " + filename + " .");
        throw new DataExchangeException(e.getCause());
    } catch (IOException e) {
        LOG.error(String.format("DataX read config file %s failed .", filename));
        throw new DataExchangeException(e.getCause());
    }

    String xpath = "/jobs/job";
    Element jobE = (Element) document.selectSingleNode(xpath);
    job.setId(jobE.attributeValue("id") == null ? "DataX_is_still_a_virgin" : jobE.attributeValue("id").trim());

    JobPluginConf readerJobConf = new JobPluginConf();
    Element readerE = (Element) document.selectSingleNode(xpath + "/loader");
    if (null == readerE)
        readerE = (Element) document.selectSingleNode(xpath + "/reader");

    String readerId = readerE.attributeValue("id");
    readerJobConf.setId(readerId == null ? "virgin-reader" : readerId.trim());
    Element readerPluinE = (Element) readerE.selectSingleNode("plugin");
    readerJobConf.setName(readerPluinE.getStringValue().trim().replace("loader", "reader").toLowerCase());

    Map<String, String> readerParamMap = new HashMap<String, String>();

    /*
     * for historic reason, we need to check concurrency node first add by
     * bazhen.csy
     */
    if (readerE.selectSingleNode("concurrency") != null) {
        Element readerConcurrencyE = (Element) readerE.selectSingleNode("concurrency");
        readerParamMap.put("concurrency", StrUtils.replaceString(readerConcurrencyE.attributeValue("core")));
    }

    List<Element> readerParamE = (List<Element>) readerE.selectNodes("param");
    for (Element e : readerParamE) {
        readerParamMap.put(e.attributeValue("key").toLowerCase(),
                StrUtils.replaceString(e.attributeValue("value").trim()));
    }

    PluginParam readerPluginParam = new DefaultPluginParam(readerParamMap);

    //      if (!readerPluginParam.hasValue("concurrency")
    //            || readerPluginParam.getIntValue("concurrency", 1) < 0) {
    //         throw new IllegalArgumentException(
    //               "Reader option [concurrency] error !");
    //      }

    readerJobConf.setPluginParams(readerPluginParam);

    List<JobPluginConf> writerJobConfs = new ArrayList<JobPluginConf>();
    List<Element> writerEs = (List<Element>) document.selectNodes(xpath + "/dumper");
    if (null == writerEs || 0 == writerEs.size())
        writerEs = (List<Element>) document.selectNodes(xpath + "/writer");

    for (Element writerE : writerEs) {
        JobPluginConf writerPluginConf = new JobPluginConf();

        String writerId = writerE.attributeValue("id");
        writerPluginConf.setId(writerId == null ? "virgin-writer" : writerId.trim());

        String destructLimit = writerE.attributeValue("destructlimit");
        if (destructLimit != null) {
            writerPluginConf.setDestructLimit(Integer.valueOf(destructLimit));
        }

        Element writerPluginE = (Element) writerE.selectSingleNode("plugin");
        writerPluginConf
                .setName(writerPluginE.getStringValue().trim().replace("dumper", "writer").toLowerCase());

        Map<String, String> writerParamMap = new HashMap<String, String>();

        /*
         * for historic reason, we need to check concurrency node add by
         * bazhen.csy
         */
        if (writerE.selectSingleNode("concurrency") != null) {
            Element writerConcurrencyE = (Element) writerE.selectSingleNode("concurrency");
            writerParamMap.put("concurrency",
                    StrUtils.replaceString(writerConcurrencyE.attributeValue("core")));
        }

        List<Element> writerParamE = (List<Element>) writerE.selectNodes("param");
        for (Element e : writerParamE) {
            writerParamMap.put(e.attributeValue("key").toLowerCase(),
                    StrUtils.replaceString(e.attributeValue("value").trim()));
        }

        PluginParam writerPluginParam = new DefaultPluginParam(writerParamMap);

        writerPluginConf.setPluginParams(writerPluginParam);
        writerJobConfs.add(writerPluginConf);
    }

    job.setReaderConf(readerJobConf);
    job.setWriterConfs(writerJobConfs);

    return job;
}

From source file:de.tudarmstadt.ukp.dkpro.c4corpus.boilerplate.standalone.HTMLBoilerplateRemoval.java

public static void processHtmlFile(File input, File outFile, boolean keepMinimalHtml) throws IOException {
    // read the html file
    String html = FileUtils.readFileToString(input, "utf-8");

    // boilerplate removal
    String cleanText;/*from   w w w.jav  a2 s.  c  o  m*/
    if (keepMinimalHtml) {
        cleanText = boilerPlateRemoval.getMinimalHtml(html, null);
    } else {
        cleanText = boilerPlateRemoval.getPlainText(html, null);
    }

    // write to the output file
    PrintWriter writer = new PrintWriter(outFile, "utf-8");
    writer.write(cleanText);

    writer.close();
}

From source file:com.wavemaker.tools.ws.XsdGenerator.java

public static List<String> generate(String xml) throws IOException, XmlException {
    File tempDir = IOUtils.createTempDirectory();
    try {//from w  w  w.j av a 2 s .c o m
        File xmlFile = new File(tempDir, "instance.xml");
        org.apache.commons.io.FileUtils.writeStringToFile(xmlFile, xml, ServerConstants.DEFAULT_ENCODING);

        List<File> schemaFiles = generate(xmlFile, tempDir);
        List<String> schemas = new ArrayList<String>();
        for (File schemaFile : schemaFiles) {
            schemas.add(FileUtils.readFileToString(schemaFile, ServerConstants.DEFAULT_ENCODING));
        }
        return schemas;
    } finally {
        IOUtils.deleteRecursive(tempDir);
    }
}

From source file:com.chrisdoyle.validation.tests.Test_Issues_23_27.java

@Test
public void checkPomNameDescriptionUrlLicenseEtcAreDefined() throws Exception {

    for (int i = 0; i < Main.allPoms.length; i++) {
        File f = new File(Main.allPoms[i]);

        String str = FileUtils.readFileToString(f, "utf-8");
        for (int k = 0; k < elementsThatShouldBeThere.length; k++) {
            if (f.getAbsolutePath().contains("hello-world-dist")
                    && "<repositories>".equalsIgnoreCase(elementsThatShouldBeThere[k])) {
                //do nothing, skip this
            } else if (f.getAbsolutePath().contains("hello-world-dist")
                    && "<dependencies>".equalsIgnoreCase(elementsThatShouldBeThere[k])) {
                //do nothing, skip this
            } else
                Assert.assertTrue(elementsThatShouldBeThere[k] + " not found in " + f.getAbsolutePath()
                        + " contents is as follows" + str, str.contains(elementsThatShouldBeThere[k]));
        }//from   w  w w.j  a v a2  s  . c o m

    }

}

From source file:com.aionemu.gameserver.configs.ingameshop.InGameShopProperty.java

public static InGameShopProperty load() {
    InGameShopProperty ing = null;//from  www .  j  a  v  a2 s  .  c  o m
    try {
        String xml = FileUtils.readFileToString(new File("./config/ingameshop/in_game_shop.xml"), "UTF-8");
        ing = JAXBUtil.deserialize(xml, InGameShopProperty.class);
    } catch (Exception e) {
        throw new RuntimeException("Failed to initialize ingameshop", e);
    }
    return ing;
}

From source file:io.stallion.services.PermaCache.java

public static String get(String key) {
    if (cache.containsKey(key)) {
        return cache.get(key);
    }//ww w . jav  a 2  s .  c om
    if (!empty(getCacheFolder())) {
        File file = new File(getCacheFolder() + "/" + DigestUtils.md5Hex(key));
        if (file.exists()) {
            try {
                String content = FileUtils.readFileToString(file, "utf-8");
                cache.put(key, content);
                return content;
            } catch (IOException e) {
                Log.exception(e, "Error reading file from disk: " + file.toString());
            }
        }
    }
    return null;
}