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.hotels.plunger.TapDataReaderTest.java

@Test
public void readLocalPartitions() throws IOException {
    File tsvFolder = temporaryFolder.newFolder("data");
    File tsvFileX = new File(tsvFolder, "X");
    File tsvFileY = new File(tsvFolder, "Y");

    FileUtils.writeStringToFile(tsvFileX, "1\thello\n", Charset.forName("UTF-8"));
    FileUtils.writeStringToFile(tsvFileY, "2\taloha\n", Charset.forName("UTF-8"));

    cascading.tap.local.PartitionTap partitionTap = new cascading.tap.local.PartitionTap(
            new cascading.tap.local.FileTap(new cascading.scheme.local.TextDelimited(valueFields),
                    tsvFolder.getAbsolutePath()),
            new DelimitedPartition(partitionFields));

    Data actual = new TapDataReader(partitionTap).read();

    assertThat(actual.orderBy(fields).asTupleEntryList(), is(expected.orderBy(fields).asTupleEntryList()));
}

From source file:com.magic.util.FileUtil.java

public static void writeString(String encoding, String s, File outFile) throws IOException {
    try {//from w  w w. ja v  a2s  .c  om
        FileUtils.writeStringToFile(outFile, s, encoding);
    } catch (IOException e) {
        Debug.logError(e, module);
        throw e;
    }
}

From source file:com.sdfl.compiler.util.CompilerFileAndFolderUtilImpl.java

@Override
public void appendAtTheEndOfFile(File pFileToWrite, String pLine) {
    try {/*w  w  w. j  a  v a 2  s  . co m*/
        FileUtils.writeStringToFile(pFileToWrite, pLine + System.lineSeparator(), true);
    } catch (IOException e) {
        throw new CannotWriteToFileException(pFileToWrite, pLine);
    }
}

From source file:com.impetus.ankush.agent.action.impl.YAMLManipulator.java

/**
 * Delete conf value.//from w w  w  .  ja v a  2s.c o  m
 * 
 * @param file
 *            the file
 * @param propertyName
 *            the property name
 * @return true, if successful
 */
public boolean deleteConfValue(String file, String objPropertyName) {

    String propertyName = (String) objPropertyName;
    Yaml yaml = new Yaml();
    try {
        InputStream fis = new FileInputStream(file);
        Object javaObject = yaml.load(fis);
        Map<String, Object> map = (Map<String, Object>) javaObject;
        if (map.containsKey(propertyName)) {
            map.remove(propertyName);
        }
        fis.close();
        // save to file
        File confFile = new File(file);
        if (!confFile.exists()) {
            System.err.println("File " + file + " does not exists.");
        }
        String dumped = yaml.dumpAsMap(map);
        FileUtils.writeStringToFile(confFile, dumped, false);

        return true;

    } catch (FileNotFoundException e) {
        System.err.println(e.getMessage());
    } catch (IOException e) {
        System.err.println(e.getMessage());
    } catch (Exception e) {
        System.err.println(e.getMessage());
    }
    return false;
}

From source file:com.meltmedia.cadmium.copyright.service.CopyrightResourceHandler.java

/**
 * Updates the copyright dates in the given file.
 *///from  w  w w .  java2s.  com
@Override
public void handleFile(File htmlFile) {
    if (jerryParser == null) {
        jerryParser = Jerry.jerry().enableHtmlMode();
        jerryParser.getDOMBuilder().setCaseSensitive(false);
        jerryParser.getDOMBuilder().setParseSpecialTagsAsCdata(true);
        jerryParser.getDOMBuilder().setSelfCloseVoidTags(false);
        jerryParser.getDOMBuilder().setConditionalCommentExpression(null);
        jerryParser.getDOMBuilder().setEnableConditionalComments(false);
        jerryParser.getDOMBuilder().setImpliedEndTags(false);
    }
    log.trace("Handling file {}", htmlFile);
    try {
        String fileContents = FileUtils.readFileToString(htmlFile);
        Jerry html = jerryParser.parse(fileContents);
        Jerry selector = html.$("[data-cadmium='copyright']");
        log.debug("Found {} copyright tags.", selector.length());
        if (selector.length() > 0) {
            selector.text(year.toString());
            log.trace("Writing updated file {}", htmlFile);
            FileUtils.writeStringToFile(htmlFile, html.html(), false);
        }
    } catch (Throwable t) {
        log.warn("Failed to update file " + htmlFile, t);
    }
}

From source file:com.thoughtworks.go.publishers.GoArtifactsManipulatorTest.java

@Before
public void setUp() throws Exception {
    httpService = mock(HttpService.class);
    artifactFolder = temporaryFolder.newFolder("artifact_folder");
    tempFile = temporaryFolder.newFile("artifact_folder/file.txt");
    FileUtils.writeStringToFile(tempFile, "some-random-data", UTF_8);
    goArtifactsManipulatorStub = new GoArtifactsManipulatorStub(httpService);
    jobIdentifier = new JobIdentifier("pipeline1", 1, "label-1", "stage1", "1", "job1");
    AgentRuntimeInfo agentRuntimeInfo = new AgentRuntimeInfo(new AgentIdentifier("h", "1", "u"),
            AgentRuntimeStatus.Idle, currentWorkingDirectory(), null, false);
    goPublisher = new DefaultGoPublisher(goArtifactsManipulatorStub, jobIdentifier,
            new BuildRepositoryRemoteStub(), agentRuntimeInfo, "utf-8");
}

From source file:com.adguard.compiler.FilterUtils.java

/**
 * Loads english filter for safari./*from   w w w  .  j  a v a2  s . c o  m*/
 * <p/>
 * The thing is that English filter is customized in case of Safari.
 * It contains big javascript rule for youtube ad blocking.
 *
 * @param destDir Destination directory.
 * @throws IOException
 */
public static void loadEnglishFilterForSafari(File destDir) throws IOException {
    log.info("Start download filter ENGLISH filter for safari");
    String downloadUrl = String.format(FILTER_DOWNLOAD_URL, ENGLISH_FILTER_ID);
    String response = UrlUtils.downloadString(new URL(downloadUrl), "UTF-8", USER_AGENT_SAFARI);
    FileUtils.writeStringToFile(new File(destDir, "filter_" + ENGLISH_FILTER_ID + ".txt"), response, "utf-8");
}

From source file:com.synopsys.integration.blackduck.service.model.pdf.RiskReportWriter.java

public void createHtmlReportFiles(final Gson gson, final File outputDirectory, final ReportData reportData)
        throws RiskReportException {
    try {/*from   w w w  .ja  v  a 2s .co m*/
        final RiskReportResourceCopier copier = new RiskReportResourceCopier(
                outputDirectory.getCanonicalPath());
        File htmlFile = null;
        try {
            final List<File> writtenFiles = copier.copy();
            for (final File file : writtenFiles) {
                if (file.getName().equals(RiskReportResourceCopier.RISK_REPORT_HTML_FILE_NAME)) {
                    htmlFile = file;
                    break;
                }
            }
        } catch (final URISyntaxException e) {
            throw new RiskReportException("Couldn't create the report: " + e.getMessage(), e);
        }
        if (htmlFile == null) {
            throw new RiskReportException(
                    "Could not find the file : " + RiskReportResourceCopier.RISK_REPORT_HTML_FILE_NAME
                            + ", the report files must not have been copied into the report directory.");
        }
        String htmlFileString = FileUtils.readFileToString(htmlFile, "UTF-8");
        final String reportString = gson.toJson(reportData);
        htmlFileString = htmlFileString.replace(RiskReportResourceCopier.JSON_TOKEN_TO_REPLACE, reportString);
        FileUtils.writeStringToFile(htmlFile, htmlFileString, "UTF-8");
    } catch (final IOException e) {
        throw new RiskReportException("Couldn't create the report: " + e.getMessage(), e);
    }
}

From source file:cat.calidos.morfeu.utils.FileSaver.java

public void save() throws SavingException {

    File destinationFile = new File(destination);
    if (destinationFile.isDirectory()) {
        log.error("Cannot save to '{}' as it is a folder and not a file", destination);
        throw new SavingException("Could not save to '" + destination + "' as it is a folder and not a file");
    }/* w w  w.j a  v a  2s.co m*/

    try {
        FileUtils.touch(destinationFile);
    } catch (IOException e) {
        log.error("Cannot save to '{}' as we cannot even touch it", destination);
        throw new SavingException("Could not save to '" + destination + "' as we cannot write to it", e);
    }
    if (!destinationFile.canWrite()) {
        log.error("Cannot save to '{}' as we cannot write to it", destination);
        throw new SavingException("Could not save to '" + destination + "' as we cannot write to it");
    }
    if (destinationFile.exists()) {
        String backupPath = destinationFile.getAbsolutePath() + BACKUP_EXTENSION;
        log.info("Renaming old '{}' to '{}'", destination, backupPath);
        File backupFile = new File(backupPath);
        if (backupFile.exists()) {
            backupFile.delete();
        }
        destinationFile.renameTo(backupFile);
    }

    try {
        FileUtils.writeStringToFile(destinationFile, content, Config.DEFAULT_CHARSET);
    } catch (IOException e) {
        log.error("Removing old '{}' to replace it with new content", destination);
        throw new SavingException("Could not save to '" + destination + "' due to IO problems", e);
    }

}

From source file:com.legstar.cobc.AbstractTest.java

/**
 * Check a result against a reference.//from w  w w .j a  v  a 2s  .c  o m
 * 
 * @throws IOException
 *             if something fails
 */
protected void check(final String result) {
    try {
        logger.debug(getClass().getSimpleName() + "-" + getName() + ":\n" + result);
        File referenceFile = new File(getReferenceFolder(), getName() + "." + REF_FILE_EXT);

        if (isCreateReferences()) {
            FileUtils.writeStringToFile(referenceFile, result, "UTF-8");
        } else {
            String expected = FileUtils.readFileToString(referenceFile, "UTF-8");
            // neutralize platform specific line separator
            assertEquals(expected.replaceAll("[\\r\\n]", ""), result.replaceAll("[\\r\\n]", ""));
        }
    } catch (IOException e) {
        logger.error("Test " + getName() + " failed", e);
        fail(e.getMessage());
    }

}