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) throws IOException 

Source Link

Document

Writes a String to a file creating the file if it does not exist using the default encoding for the VM.

Usage

From source file:de.tudarmstadt.ukp.experiments.argumentation.sequence.evaluation.GenerateCrossDomainCVReport.java

/**
 * Merges id2outcome files from sub-folders with cross-domain and creates a new folder
 * with overall results//from   w w w .j a v a2  s  .  c  o  m
 *
 * @param folder folder
 * @throws java.io.IOException
 */
public static void aggregateDomainResults(File folder, String subDirPrefix, final String taskFolderSubText,
        String outputFolderName) throws IOException {
    // list all sub-folders
    File[] folders = folder.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory() && pathname.getName().contains(taskFolderSubText);
        }
    });

    if (folders.length == 0) {
        throw new IllegalArgumentException("No sub-folders 'SVMHMMTestTask*' found in " + folder);
    }

    // write to a file
    File outFolder = new File(folder, outputFolderName);
    File output = new File(outFolder, subDirPrefix);
    output.mkdirs();

    File outCsv = new File(output, TOKEN_LEVEL_PREDICTIONS_CSV);

    CSVPrinter csvPrinter = new CSVPrinter(new FileWriter(outCsv), SVMHMMUtils.CSV_FORMAT);
    csvPrinter.printComment(SVMHMMUtils.CSV_COMMENT);

    ConfusionMatrix cm = new ConfusionMatrix();

    for (File domain : folders) {
        File tokenLevelPredictionsCsv = new File(domain, subDirPrefix + "/" + TOKEN_LEVEL_PREDICTIONS_CSV);

        if (!tokenLevelPredictionsCsv.exists()) {
            throw new IllegalArgumentException(
                    "Cannot locate tokenLevelPredictions.csv: " + tokenLevelPredictionsCsv);
        }

        CSVParser csvParser = new CSVParser(new FileReader(tokenLevelPredictionsCsv),
                CSVFormat.DEFAULT.withCommentMarker('#'));

        for (CSVRecord csvRecord : csvParser) {
            // copy record
            csvPrinter.printRecord(csvRecord);

            // update confusion matrix
            cm.increaseValue(csvRecord.get(0), csvRecord.get(1));
        }
    }

    // write to file
    FileUtils.writeStringToFile(new File(outFolder, "confusionMatrix.txt"), cm.toString() + "\n"
            + cm.printNiceResults() + "\n" + cm.printLabelPrecRecFm() + "\n" + cm.printClassDistributionGold());

    // write csv
    IOUtils.closeQuietly(csvPrinter);
}

From source file:models.logic.CipherDecipher.java

public static void keyToFile(SecretKey key, String keyPath) throws IOException {
    File file = new File(keyPath);
    char[] hex = encodeHex(key.getEncoded());
    FileUtils.writeStringToFile(file, String.valueOf(hex));
}

From source file:de.fu_berlin.inf.dpp.misc.pico.DotGraphMonitor.java

public void save(File file) {
    try {/*  w w w.  j  av  a 2 s .c  om*/
        String output = "digraph G {\n" + "  node [shape=box];\n" + "  rank=source;\n"
                + "  rankdir=LR;\n  node[penwidth=2.0];\n" + getClassDependencyGraph() + "\n" + "}";

        FileUtils.writeStringToFile(file, output);
    } catch (Exception e) {
        log.error("Internal error: ", e);
    }
}

From source file:br.univali.celine.lms.integration.ContentPackageBuilder.java

public void build(String organizationName, String outputFileName) throws Exception {

    String sdir = tempDir + "/" + organizationName;
    File fdir = new File(sdir);
    FileUtils.deleteDirectory(new File(tempDir));

    fdir.mkdirs();//from w  w  w  .  ja v a 2 s  . co m

    ContentPackage cp = ContentPackage.buildBasic(organizationName, organizationName,
            new ContentPackageReader20043rd());
    Organization org = cp.getOrganizations().getDefaultOrganization();

    Zip zip = new Zip();
    for (FileItem fi : fileItens) {

        zip.unzip(fi.zipFile, new File(sdir + "/" + fi.itemName));
        Item20043rd item = Item20043rd.buildBasic(fi.itemName, fi.itemName);
        item.setIdentifierref("RES-" + fi.itemName);

        org.addItem(item);

        Resource res = new Resource();
        res.setHref(fi.itemName + "/" + fi.itemFileRoot);
        res.setIdentifier(item.getIdentifierref());
        res.setScormType("sco");
        res.setType("webcontent");

        cp.getResources().addResource(res);

    }

    FileUtils.writeStringToFile(new File(sdir + "/imsmanifest.xml"), cp.toString());

    zip.zipDir(outputFileName, sdir);

}

From source file:io.restassured.itest.java.FileUploadingITest.java

@Test
public void can_upload_file_with_custom_content_type() throws IOException {
    // Given//  w  w w.ja  va 2s  .c o m
    File file = folder.newFile("my.txt");
    FileUtils.writeStringToFile(file, "Hello World");

    // When
    given().contentType("application/something").body(file).when().post("/reflect").then().statusCode(200)
            .body(equalTo("Hello World"));
}

From source file:com.ikanow.aleph2.analytics.spark.services.SparkCompilerService.java

/** Compiles a scala class
 * @param script//from ww w. ja  va  2 s .c o m
 * @param clazz_name
 * @return
 * @throws IOException
 * @throws InstantiationException
 * @throws IllegalAccessException
 * @throws ClassNotFoundException
 */
public Tuple2<ClassLoader, Object> buildClass(final String script, final String clazz_name,
        final Optional<IBucketLogger> logger)
        throws IOException, InstantiationException, IllegalAccessException, ClassNotFoundException {
    final String relative_dir = "./script_classpath/";
    new File(relative_dir).mkdirs();

    final File source_file = new File(relative_dir + clazz_name + ".scala");
    FileUtils.writeStringToFile(source_file, script);

    final String this_path = LiveInjector.findPathJar(this.getClass(), "./dummy.jar");
    final File f = new File(this_path);
    final File fp = new File(f.getParent());
    final String classpath = Arrays.stream(fp.listFiles()).map(ff -> ff.toString())
            .filter(ff -> ff.endsWith(".jar")).collect(Collectors.joining(":"));

    // Need this to make the URL classloader be used, not the system classloader (which doesn't know about Aleph2..)

    final Settings s = new Settings();
    s.classpath().value_$eq(System.getProperty("java.class.path") + classpath);
    s.usejavacp().scala$tools$nsc$settings$AbsSettings$AbsSetting$$internalSetting_$eq(true);
    final StoreReporter reporter = new StoreReporter();
    final Global g = new Global(s, reporter);
    final Run r = g.new Run();
    r.compile(JavaConverters.asScalaBufferConverter(Arrays.<String>asList(source_file.toString())).asScala()
            .toList());

    if (reporter.hasErrors() || reporter.hasWarnings()) {
        final String errors = "Compiler: Errors/warnings (**to get to user script line substract 22**): "
                + JavaConverters.asJavaSetConverter(reporter.infos()).asJava().stream()
                        .map(info -> info.toString()).collect(Collectors.joining(" ;; "));
        logger.ifPresent(l -> l.log(reporter.hasErrors() ? Level.ERROR : Level.DEBUG, false, () -> errors,
                () -> "SparkScalaInterpreterTopology", () -> "compile"));

        //ERROR:
        if (reporter.hasErrors()) {
            System.err.println(errors);
        }
    }
    // Move any class files (eg including sub-classes)
    Arrays.stream(fp.listFiles()).filter(ff -> ff.toString().endsWith(".class"))
            .forEach(Lambdas.wrap_consumer_u(ff -> {
                FileUtils.moveFile(ff, new File(relative_dir + ff.getName()));
            }));

    // Create a JAR file...

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    final JarOutputStream target = new JarOutputStream(new FileOutputStream("./script_classpath.jar"),
            manifest);
    Arrays.stream(new File(relative_dir).listFiles()).forEach(Lambdas.wrap_consumer_i(ff -> {
        JarEntry entry = new JarEntry(ff.getName());
        target.putNextEntry(entry);
        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(ff))) {
            byte[] buffer = new byte[1024];
            while (true) {
                int count = in.read(buffer);
                if (count == -1)
                    break;
                target.write(buffer, 0, count);
            }
            target.closeEntry();
        }
    }));
    target.close();

    final String created = "Created = " + new File("./script_classpath.jar").toURI().toURL() + " ... "
            + Arrays.stream(new File(relative_dir).listFiles()).map(ff -> ff.toString())
                    .collect(Collectors.joining(";"));
    logger.ifPresent(l -> l.log(Level.DEBUG, true, () -> created, () -> "SparkScalaInterpreterTopology",
            () -> "compile"));

    final Tuple2<ClassLoader, Object> o = Lambdas.get(Lambdas.wrap_u(() -> {
        _cl.set(new java.net.URLClassLoader(
                Arrays.asList(new File("./script_classpath.jar").toURI().toURL()).toArray(new URL[0]),
                Thread.currentThread().getContextClassLoader()));
        Object o_ = _cl.get().loadClass("ScriptRunner").newInstance();
        return Tuples._2T(_cl.get(), o_);
    }));
    return o;
}

From source file:com.thoughtworks.go.server.service.support.ServerStatusService.java

private void populateServerInfo(File serverInfoFile) throws IOException {
    FileUtils.writeStringToFile(serverInfoFile, serverInfo());
}

From source file:com.logsniffer.model.file.RollingLogSourceTest.java

@Before
public void setUp() throws IOException, InterruptedException {
    logDir = new File(File.createTempFile("log", "log").getPath() + "dir");
    logDir.mkdirs();/* w w w .  ja  v  a  2s. c om*/
    FileUtils.writeStringToFile(new File(logDir, "server.log"), "live\n");
    FileUtils.writeStringToFile(new File(logDir, "server.log.2013-03-27"), "log from 2013-03-27\n");
    Thread.sleep(1200);
    FileUtils.writeStringToFile(new File(logDir, "server.log.2013-03-26"), "log from 2013-03-26\n");
}

From source file:aurelienribon.utils.TemplateManager.java

/**
 * Opens the given file, processes its variables, and overwrites the file
 * with the result.//from   w w w.  j av a 2  s .  c om
 * @throws IOException
 */
public void processOver(File file) throws IOException {
    String input = FileUtils.readFileToString(file);
    FileUtils.writeStringToFile(file, process(input));
}

From source file:de.tudarmstadt.ukp.dkpro.tc.core.feature.ContextMetaCollector_ImplBase.java

@Override
public void collectionProcessComplete() throws AnalysisEngineProcessException {
    super.collectionProcessComplete();

    try {/* w  w w .  j  a v  a2s . c om*/
        FileUtils.writeStringToFile(contextFile, sb.toString());
    } catch (IOException e) {
        throw new AnalysisEngineProcessException(e);
    }
}