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

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

Introduction

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

Prototype

public static void writeStringToFile(File file, String data, String encoding) throws IOException 

Source Link

Document

Writes a String to a file creating the file if it does not exist.

Usage

From source file:com.hangum.tadpole.engine.sql.util.export.HTMLExporter.java

/**
 * make content file// w  ww.j  a  v a2  s  .c  om
 * 
 * @param tableName
 * @param rsDAO
 * @return
 * @throws Exception
 */
public static String makeContentFile(String tableName, QueryExecuteResultDTO rsDAO) throws Exception {
    // full text
    String strTmpDir = PublicTadpoleDefine.TEMP_DIR + tableName + System.currentTimeMillis()
            + PublicTadpoleDefine.DIR_SEPARATOR;
    String strFile = tableName + ".html";
    String strFullPath = strTmpDir + strFile;

    FileUtils.writeStringToFile(new File(strFullPath), HTMLDefine.sbHtml, true);
    FileUtils.writeStringToFile(new File(strFullPath), "<table class='tg'>", true);

    // make content
    List<Map<Integer, Object>> dataList = rsDAO.getDataList().getData();
    // column .
    Map<Integer, String> mapLabelName = rsDAO.getColumnLabelName();
    StringBuffer sbHead = new StringBuffer();
    sbHead.append(String.format(strHead, "#"));
    for (int i = 1; i < mapLabelName.size(); i++) {
        sbHead.append(String.format(strHead, mapLabelName.get(i)));
    }
    String strLastColumnName = String.format(strGroup, sbHead.toString());

    // header
    FileUtils.writeStringToFile(new File(strFullPath), strLastColumnName, true);

    // body start
    StringBuffer sbBody = new StringBuffer("");
    for (int i = 0; i < dataList.size(); i++) {
        Map<Integer, Object> mapColumns = dataList.get(i);

        StringBuffer sbTmp = new StringBuffer();
        sbTmp.append(String.format(strHead, "" + (i + 1))); //$NON-NLS-1$
        for (int j = 1; j < mapColumns.size(); j++) {
            String strValue = mapColumns.get(j) == null ? "" : "" + mapColumns.get(j);
            sbTmp.append(String.format(strContent, StringEscapeUtils.unescapeHtml(strValue))); //$NON-NLS-1$
        }
        sbBody.append(String.format(strGroup, sbTmp.toString()));

        if ((i % DATA_COUNT) == 0) {
            FileUtils.writeStringToFile(new File(strFullPath), sbBody.toString(), true);
            sbBody.delete(0, sbBody.length());
        }
    }

    if (sbBody.length() > 0) {
        FileUtils.writeStringToFile(new File(strFullPath), sbBody.toString(), true);
    }

    FileUtils.writeStringToFile(new File(strFullPath), "</table>", true);

    return strFullPath;
}

From source file:com.thoughtworks.go.config.ArtifactPropertyConfigTest.java

private File createSrcFile() throws IOException {
    String content = "<buildplans>\n" + "          <buildplan name=\"test\">\n" + "            <artifacts>\n"
            + "              <artifact src=\"target\\connectfour.jar\" dest=\"dist\\jars\" />\n"
            + "              <artifact src=\"target\\test-results\" dest=\"testoutput\" type=\"junit\" />\n"
            + "              <artifact src=\"build.xml\" />\n" + "            </artifacts>\n"
            + "            <tasks>\n" + "              <ant workingdir=\"dev\" target=\"all\" />\n"
            + "            </tasks>\n" + "          </buildplan>\n" + "        </buildplans>";
    File file = new File(workspace, "xmlfile");
    FileUtils.writeStringToFile(file, content, "UTF-8");
    return file;/*from w w  w  . ja  v  a2 s.  co m*/
}

From source file:com.sangupta.pep.Generator.java

private void write() throws IOException {
    // get the html presentation
    String html = this.render();

    // write the presentation code
    FileUtils.writeStringToFile(new File(parentDir, options.getDestinationFile()), html, options.getEncoding());

    // copy the theme if specified
    if (this.options.isCopyTheme()) {
        copyResource(getScreenCSS());/*w w  w.  j a  v a  2s .co  m*/
        copyResource(getPrintCSS());
        copyResource(getJS());
    }
}

From source file:com.mtt.myapp.operation.service.AnnouncementService.java

/**
 * Save content to announcement.conf file.
 * /*  w  w w .ja va2  s. c  o m*/
 * @param content
 *            file content.
 * @return save successfully or not.
 */
@CacheEvict("announce")
public boolean save(String content) {
    try {
        FileUtils.writeStringToFile(home.getSubFile("announce.properties"), content, "UTF-8");
    } catch (IOException e) {
        LOGGER.error("Error while writing announcement file.");
        return false;
    }
    return true;
}

From source file:com.uwsoft.editor.data.manager.SceneDataManager.java

public void saveScene(SceneVO vo) {
    try {//from   w  w  w . j a  va 2  s  .c  om
        FileUtils
                .writeStringToFile(
                        new File(dataManager.getCurrentWorkingPath() + "/"
                                + dataManager.currentProjectVO.projectName + "/scenes/" + vo.sceneName + ".dt"),
                        vo.constructJsonString(), "utf-8");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:abfab3d.shapejs.Project.java

public void save(String file) throws IOException {
    EvaluatedScript escript = m_script.getEvaluatedScript();
    Map<String, Parameter> scriptParams = escript.getParamMap();
    Gson gson = JSONParsing.getJSONParser();

    String code = escript.getCode();

    Path workingDirName = Files.createTempDirectory("saveScript");
    String workingDirPath = workingDirName.toAbsolutePath().toString();
    Map<String, Object> params = new HashMap<String, Object>();

    // Write the script to file
    File scriptFile = new File(workingDirPath + "/main.js");
    FileUtils.writeStringToFile(scriptFile, code, "UTF-8");

    // Loop through params and create key/pair entries
    for (Map.Entry<String, Parameter> entry : scriptParams.entrySet()) {
        String name = entry.getKey();
        Parameter pval = entry.getValue();

        if (pval.isDefaultValue())
            continue;

        ParameterType type = pval.getType();

        switch (type) {
        case URI:
            URIParameter urip = (URIParameter) pval;
            String u = (String) urip.getValue();

            //                   System.out.println("*** uri: " + u);
            File f = new File(u);

            String fileName = null;

            // TODO: This is hacky. If the parameter value is a directory, then assume it was
            //       originally a zip file, and its contents were extracted in the directory.
            //       Search for the zip file in the directory and copy that to the working dir.
            if (f.isDirectory()) {
                File[] files = f.listFiles();
                for (int i = 0; i < files.length; i++) {
                    String fname = files[i].getName();
                    if (fname.endsWith(".zip")) {
                        fileName = fname;
                        f = files[i];//www  . j  a va2 s.c  om
                    }
                }
            } else {
                fileName = f.getName();
            }

            params.put(name, fileName);

            // Copy the file to working directory
            FileUtils.copyFile(f, new File(workingDirPath + "/" + fileName), true);
            break;
        case LOCATION:
            LocationParameter lp = (LocationParameter) pval;
            Vector3d p = lp.getPoint();
            Vector3d n = lp.getNormal();
            double[] point = { p.x, p.y, p.z };
            double[] normal = { n.x, n.y, n.z };
            //                   System.out.println("*** lp: " + java.util.Arrays.toString(point) + ", " + java.util.Arrays.toString(normal));
            Map<String, double[]> loc = new HashMap<String, double[]>();
            loc.put("point", point);
            loc.put("normal", normal);
            params.put(name, loc);
            break;
        case AXIS_ANGLE_4D:
            AxisAngle4dParameter aap = (AxisAngle4dParameter) pval;
            AxisAngle4d a = (AxisAngle4d) aap.getValue();
            params.put(name, a);
            break;
        case DOUBLE:
            DoubleParameter dp = (DoubleParameter) pval;
            Double d = (Double) dp.getValue();
            //                   System.out.println("*** double: " + d);

            params.put(name, d);
            break;
        case INTEGER:
            IntParameter ip = (IntParameter) pval;
            Integer i = ip.getValue();
            //                   System.out.println("*** int: " + pval);
            params.put(name, i);
            break;
        case STRING:
            StringParameter sp = (StringParameter) pval;
            String s = sp.getValue();
            //                   System.out.println("*** string: " + s);
            params.put(name, s);
            break;
        case COLOR:
            ColorParameter cp = (ColorParameter) pval;
            Color c = cp.getValue();
            //                   System.out.println("*** string: " + s);
            params.put(name, c.toHEX());
            break;
        case ENUM:
            EnumParameter ep = (EnumParameter) pval;
            String e = ep.getValue();
            //                   System.out.println("*** string: " + s);
            params.put(name, e);
            break;
        default:
            params.put(name, pval);
        }

    }

    if (params.size() > 0) {
        String paramsJson = gson.toJson(params);
        File paramFile = new File(workingDirPath + "/" + "params.json");
        FileUtils.writeStringToFile(paramFile, paramsJson, "UTF-8");
    }

    File[] files = (new File(workingDirPath)).listFiles();

    FileOutputStream fos = new FileOutputStream(file);
    ZipOutputStream zos = new ZipOutputStream(fos);
    System.out.println("*** Num files to zip: " + files.length);

    try {
        byte[] buffer = new byte[1024];

        for (int i = 0; i < files.length; i++) {
            //                if (files[i].getName().endsWith(".zip")) continue;

            System.out.println("*** Adding file: " + files[i].getName());
            FileInputStream fis = new FileInputStream(files[i]);
            ZipEntry ze = new ZipEntry(files[i].getName());
            zos.putNextEntry(ze);

            int len;
            while ((len = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, len);
            }

            fis.close();
        }
    } finally {
        zos.closeEntry();
        zos.close();
    }
}

From source file:io.jexiletools.es.ExileToolsSearchClientTest.java

@Test
public void testGrabItemMapping() throws Exception {
    HttpResponse<String> httpResponse = Unirest.get("http://api.exiletools.com/index/_mapping")
            .header("Authorization", "DEVELOPMENT-Indexer").asString();
    String body = httpResponse.getBody();
    File mapping = new File("poe-mapping.json");
    FileUtils.writeStringToFile(mapping, body, Charsets.UTF_8);
}

From source file:mysynopsis.HTMLWriter.java

public static String writeHTML() throws IOException {

    JSONWriter.writeData();// w  w  w.ja  v a2  s .c  om

    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:de.pixida.logtest.automatondefinitions.JsonAutomatonDefinitionTest.java

@Test(expected = AutomatonLoadingException.class)
public void testExceptionIsThrownIfADestinationNodeIsNotFound() throws IOException {
    final JSONObject config = SomeTestAutomaton.getRawConfigJson();
    config.getJSONArray("nodes").getJSONObject(0).getJSONArray("outgoingEdges").getJSONObject(0)
            .put("destination", "INVALID_DEST_NODE");
    final File rewrittenConfig = this.testFolder.newFile();
    FileUtils.writeStringToFile(rewrittenConfig, config.toString(), JsonAutomatonDefinition.EXPECTED_CHARSET);
    this.loadAutomatonDefinitionFromFile(rewrittenConfig);
}

From source file:com.thoughtworks.go.config.materials.mercurial.HgMaterialDockerTest.java

@Test
public void shouldNotRefreshWorkingDirectoryIfPasswordIsNotSetInHgrcFileButIsAvailableInMaterialUrl()
        throws Exception {
    HgMaterial material = new HgMaterial("http://user1:password@localhost:9999", null);
    final List<Modification> modifications = material.latestModification(workingFolder,
            new TestSubprocessExecutionContext());
    final File unversionedFile = new File(workingFolder, "unversioned.txt");
    FileUtils.writeStringToFile(unversionedFile, "something", UTF_8);
    assertTrue(unversionedFile.exists());

    material.modificationsSince(workingFolder, new StringRevision(modifications.get(0).getRevision()),
            new TestSubprocessExecutionContext());
    assertTrue(unversionedFile.exists());
}