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.thoughtworks.go.server.web.FileViewTest.java

@Before
public void setUp() throws Exception {
    temporaryFolder.create();/*from   w ww.  ja  v  a 2s  .  c  o m*/
    mockRequest = new MockHttpServletRequest();
    mockResponse = new MockHttpServletResponse();
    mockServletContext = mock(ServletContext.class);
    view = new FileView();
    view.setServletContext(mockServletContext);
    file = temporaryFolder.newFile("file.txt");
    FileUtils.writeStringToFile(file, "hello", UTF_8);
}

From source file:cd.go.contrib.elasticagents.docker.DockerClientFactory.java

private static void setupCerts(PluginSettings pluginSettings, DefaultDockerClient.Builder builder)
        throws IOException, DockerCertificateException {
    if (isBlank(pluginSettings.getDockerCACert()) || isBlank(pluginSettings.getDockerClientCert())
            || isBlank(pluginSettings.getDockerClientKey())) {
        LOG.warn("Missing docker certificates, will attempt to connect without certificates");
        return;/* w ww  .ja v  a 2 s.c  om*/
    }

    Path certificateDir = Files.createTempDirectory(UUID.randomUUID().toString());
    File tempDirectory = certificateDir.toFile();

    try {
        FileUtils.writeStringToFile(new File(tempDirectory, DockerCertificates.DEFAULT_CA_CERT_NAME),
                pluginSettings.getDockerCACert(), StandardCharsets.UTF_8);
        FileUtils.writeStringToFile(new File(tempDirectory, DockerCertificates.DEFAULT_CLIENT_CERT_NAME),
                pluginSettings.getDockerClientCert(), StandardCharsets.UTF_8);
        FileUtils.writeStringToFile(new File(tempDirectory, DockerCertificates.DEFAULT_CLIENT_KEY_NAME),
                pluginSettings.getDockerClientKey(), StandardCharsets.UTF_8);
        builder.dockerCertificates(new DockerCertificates(certificateDir));
    } finally {
        FileUtils.deleteDirectory(tempDirectory);
    }
}

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

/**
 * Writes a file from a string with a specified encoding.
 *
 * @param path//www  .  j a v  a  2 s .c om
 * @param name
 * @param encoding
 * @param s
 * @throws IOException
 */
public static void writeString(String path, String name, String encoding, String s) throws IOException {
    String fileName = getPatchedFileName(path, name);
    if (UtilValidate.isEmpty(fileName)) {
        throw new IOException("Cannot obtain buffered writer for an empty filename!");
    }

    try {
        FileUtils.writeStringToFile(new File(fileName), s, encoding);
    } catch (IOException e) {
        Debug.logError(e, module);
        throw e;
    }
}

From source file:cz.incad.kramerius.client.CacheServlet.java

private void saveToFile(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {/*from  w  w  w  .  java2 s  .c  o m*/
        String filename = getPath() + req.getParameter("f");
        String content = req.getParameter("c");
        File f = new File(filename);
        FileUtils.writeStringToFile(f, content, "UTF-8");

        resp.getWriter().write("File saved");
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Could not save file: " + e.toString());
    }
}

From source file:io.anserini.doc.GenerateRegressionDocsTest.java

@Test
public void main() throws Exception {
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    URL resource = GenerateRegressionDocsTest.class.getResource("/regression/all.yaml");
    DataModel data = mapper.readValue(Paths.get(resource.toURI()).toFile(), DataModel.class);
    //System.out.println(ReflectionToStringBuilder.toString(data, ToStringStyle.MULTI_LINE_STYLE));

    for (String collection : data.getCollections().keySet()) {
        Map<String, String> valuesMap = new HashMap<>();
        valuesMap.put("index_cmds", data.generateIndexingCommand(collection));
        valuesMap.put("ranking_cmds", data.generateRankingCommand(collection));
        valuesMap.put("eval_cmds", data.generateEvalCommand(collection));
        valuesMap.put("effectiveness", data.generateEffectiveness(collection));
        StrSubstitutor sub = new StrSubstitutor(valuesMap);
        URL template = GenerateRegressionDocsTest.class
                .getResource(String.format("/docgen/templates/%s.template", collection));
        Scanner scanner = new Scanner(Paths.get(template.toURI()).toFile(), "UTF-8");
        String text = scanner.useDelimiter("\\A").next();
        scanner.close();//from   w ww . j  a v a2  s.  c om
        String resolvedString = sub.replace(text);

        FileUtils.writeStringToFile(new File(String.format("docs/experiments-%s.md", collection)),
                resolvedString, "UTF-8");
    }
}

From source file:de.nrw.hbz.regal.sync.ingest.OpusDownloader.java

private void downloadXMetaDissPlus(File dir, String pid) throws IOException {

    String url = server + pid;/*from   w w w  .ja v a  2  s.  com*/
    logger.info("Download: " + url);
    URL dataStreamUrl = new URL(url);
    File dataStreamFile = new File(dir.getAbsolutePath() + File.separator + "" + pid + ".xml");
    // dataStreamFile.createNewFile();

    logger.info("Save: " + dataStreamFile.getAbsolutePath());

    String data = null;
    StringWriter writer = new StringWriter();
    IOUtils.copy(dataStreamUrl.openStream(), writer);
    data = writer.toString();
    FileUtils.writeStringToFile(dataStreamFile, data, "utf-8");
}

From source file:com.thoughtworks.go.security.ResetCipher.java

public void setupDESCipherFile(String cipher) throws IOException {
    ReflectionUtil.setField(desCipherProvider, "cachedKey", null);
    FileUtils.writeStringToFile(systemEnvironment.getDESCipherFile(), cipher, UTF_8);
}

From source file:gov.va.chir.tagline.dao.DatasetFeatureSaver.java

private void saveHeader() throws IOException {
    final StringBuilder builder = new StringBuilder();

    builder.append(DatasetUtil.DOC_ID);/*w  ww .j  a v  a 2s .co m*/
    builder.append("\t");

    builder.append(DatasetUtil.LINE_ID);
    builder.append("\t");

    for (String feature : docFeatures) {
        builder.append(feature);
        builder.append("\t");
    }

    for (String feature : lineFeatures) {
        builder.append(feature);
        builder.append("\t");
    }

    builder.append(DatasetUtil.LABEL);
    builder.append("\t");

    builder.append(PRED_PROB);
    builder.append("\t");

    builder.append(PRED_LABEL);
    builder.append(System.getProperty("line.separator"));

    FileUtils.writeStringToFile(file, builder.toString(), false);
}

From source file:de.dal33t.powerfolder.util.AddLicenseHeader.java

public static void addLicInfo(Path f) {
    try {/*  w  w  w .jav  a 2s  .  co m*/
        if (f.toAbsolutePath().toString().contains("\\jwf\\jwf")) {
            System.out.println("Skip: " + f.toRealPath());
            return;
        }
        if (f.toAbsolutePath().toString().contains("org\\jdesktop\\swinghelper")) {
            System.out.println("Skip: " + f.toRealPath());
            return;
        }
        String content = FileUtils.readFileToString(f.toFile(), "UTF-8");
        int i = content.indexOf("package");

        //            if (i != 693) {
        //                System.out.println("Skip: " + f.getCanonicalPath() + ": " + i);
        //                return;
        //            }
        boolean dennis = content.contains("@author Dennis");
        if (dennis) {
            System.err.println("Dennis: " + f.toRealPath() + ": " + i);
            content = LIC_INFO_DENNIS + content.substring(i, content.length());
        } else {
            System.out.println("Onlyme: " + f.toRealPath() + ": " + i);
            content = LIC_INFO + content.substring(i, content.length());
        }
        //
        // System.out.println(content);
        FileUtils.writeStringToFile(f.toFile(), content, "UTF-8");
        // throw new RuntimeException();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:edu.wpi.checksims.util.output.OutputAsFilePrinter.java

/**
 * Print given similarity matrix to file.
 *
 * @param toPrint Matrix to print/*  w  w  w  .ja v a2  s .  co m*/
 * @param printWith Output strategy to use
 */
@Override
public void print(SimilarityMatrix toPrint, MatrixPrinter printWith) {
    checkNotNull(toPrint);
    checkNotNull(printWith);

    File outputTo = new File(baseName.getAbsolutePath() + "." + printWith.getName());

    logs.info("Writing " + printWith.getName() + " output to file " + outputTo.getName());

    try {
        FileUtils.writeStringToFile(outputTo, printWith.printMatrix(toPrint), StandardCharsets.UTF_8);
    } catch (IOException | InternalAlgorithmError e) {
        throw new RuntimeException("Could not write output to file", e);
    }
}