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.googlecode.dex2jar.bin_gen.BinGen.java

/**
 * @param args/*ww w  . j  a v  a 2  s  .  c om*/
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    Properties p = new Properties();
    p.load(BinGen.class.getResourceAsStream("class.cfg"));

    String bat = FileUtils.readFileToString(
            new File("src/main/resources/com/googlecode/dex2jar/bin_gen/bat_template"), "UTF-8");
    String sh = FileUtils.readFileToString(
            new File("src/main/resources/com/googlecode/dex2jar/bin_gen/sh_template"), "UTF-8");

    File binDir = new File("src/main/bin");
    String setclasspath = FileUtils.readFileToString(
            new File("src/main/resources/com/googlecode/dex2jar/bin_gen/setclasspath.bat"), "UTF-8");
    FileUtils.writeStringToFile(new File(binDir, "setclasspath.bat"), setclasspath, "UTF-8");
    for (Object key : p.keySet()) {
        String name = key.toString();
        FileUtils.writeStringToFile(new File(binDir, key.toString() + ".sh"),
                sh.replaceAll("__@class_name@__", p.getProperty(name)), "UTF-8");
        FileUtils.writeStringToFile(new File(binDir, key.toString() + ".bat"),
                bat.replaceAll("__@class_name@__", p.getProperty(name)), "UTF-8");
    }
}

From source file:com.discursive.jccook.io.FileCopyExample.java

public static void main(String[] args) {
    try {/*  ww w .  j  a  v  a2 s  . co m*/
        File src = new File("test.dat");
        File dest = new File("test.dat.bak");

        FileUtils.copyFile(src, dest);
    } catch (IOException ioe) {
        System.out.println("Problem copying file.");
    }

    try {
        File src = new File("test.dat");
        File dir = new File("./temp");

        FileUtils.copyFileToDirectory(src, dir);
    } catch (IOException ioe) {
        System.out.println("Problem copying file to dir.");
    }

    try {
        String string = "Blah blah blah";
        File dest = new File("test.tmp");

        FileUtils.writeStringToFile(dest, string, "ISO-8859-1");
    } catch (IOException ioe) {
        System.out.println("Error writing out a String.");
    }
}

From source file:de.tudarmstadt.ukp.argumentation.cleaning.DataCleaner.java

public static void main(String[] args) throws Exception {
    // default path
    File dataDir = new File("data/");

    // or from parameters
    if (args.length > 0) {
        dataDir = new File(args[0]);
    }//from  www. jav a 2  s . co m

    Collection<File> files = FileUtils.listFiles(dataDir, new String[] { "txt" }, true);

    if (files.isEmpty()) {
        throw new IllegalArgumentException("No .txt files found in " + dataDir);
    }

    for (File file : files) {
        String text = FileUtils.readFileToString(file, "utf-8");

        // cleaning
        String normalized = TextCleaningUtils.normalize(text);

        // and write back
        FileUtils.writeStringToFile(file, normalized, "utf-8");
    }
}

From source file:com.thoughtworks.go.server.JUnitReportGenerator.java

public static void main(String[] args) throws Exception {
    Document doc = new SAXReader().read(new FileInputStream(new File("/home/cruise/sample_junit.xml")));
    Element suite = (Element) doc.selectSingleNode("//testsuite");
    Element rootElement = doc.getRootElement();
    for (int i = 0; i < 50000; i++) {
        Element copy = suite.createCopy();
        setAttr(i, copy, "name");
        setAttr(i, copy, "hostname");
        List<Element> elements = copy.selectNodes(".//testcase");
        for (Element element : elements) {
            setAttr(i, element, "classname");
            setAttr(i, element, "name");
        }/*from  w  ww. j  ava  2 s . c o  m*/
        rootElement.add(copy);
    }
    FileUtils.writeStringToFile(new File("/tmp/repo/imagine.xml"), doc.asXML(), UTF_8);
}

From source file:dhr.uploadtomicrobit.FirmwareGenerator.java

/**
 * @param args// w ww  .  ja v  a 2 s. c o m
 * @throws IOException 
 */

public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    int[] ar = { 1, 2, 3, 66, 77, 8, 89, 123 };

    String simple = "# Add your Python code here. E.g.\n";
    simple = simple + "from microbit import *\n";
    simple = simple + "while True:\n";
    simple = simple + "\tdisplay.scroll('Great It Works!')\n";
    simple = simple + "\tdisplay.show(Image.HEART)\n";
    simple = simple + "\tsleep(2000)\n";

    String script = simple;

    FirmwareGenerator fg = new FirmwareGenerator();

    String output = fg.generateFirmware(simple);

    File file = new File("firmware.hex");
    FileUtils.writeStringToFile(file, output.toString(), Charset.forName("ISO-8859-1"));

}

From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step5GoldLabelEstimator.java

@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
    String inputDir = args[0];/*from ww  w.j a  va 2  s.  c o m*/
    File outputDir = new File(args[1]);

    if (!outputDir.exists()) {
        outputDir.mkdirs();
    }

    // we will process only a subset first
    List<AnnotatedArgumentPair> allArgumentPairs = new ArrayList<>();

    Collection<File> files = IOHelper.listXmlFiles(new File(inputDir));

    for (File file : files) {
        allArgumentPairs.addAll((List<AnnotatedArgumentPair>) XStreamTools.getXStream().fromXML(file));
    }

    // collect turkers and csv
    List<String> turkerIDs = extractAndSortTurkerIDs(allArgumentPairs);
    String preparedCSV = prepareCSV(allArgumentPairs, turkerIDs);

    // save CSV and run MACE
    Path tmpDir = Files.createTempDirectory("mace");
    File maceInputFile = new File(tmpDir.toFile(), "input.csv");
    FileUtils.writeStringToFile(maceInputFile, preparedCSV, "utf-8");

    File outputPredictions = new File(tmpDir.toFile(), "predictions.txt");
    File outputCompetence = new File(tmpDir.toFile(), "competence.txt");

    // run MACE
    MACE.main(new String[] { "--iterations", "500", "--threshold", String.valueOf(MACE_THRESHOLD), "--restarts",
            "50", "--outputPredictions", outputPredictions.getAbsolutePath(), "--outputCompetence",
            outputCompetence.getAbsolutePath(), maceInputFile.getAbsolutePath() });

    // read back the predictions and competence
    List<String> predictions = FileUtils.readLines(outputPredictions, "utf-8");

    // check the output
    if (predictions.size() != allArgumentPairs.size()) {
        throw new IllegalStateException("Wrong size of the predicted file; expected " + allArgumentPairs.size()
                + " lines but was " + predictions.size());
    }

    String competenceRaw = FileUtils.readFileToString(outputCompetence, "utf-8");
    String[] competence = competenceRaw.split("\t");
    if (competence.length != turkerIDs.size()) {
        throw new IllegalStateException(
                "Expected " + turkerIDs.size() + " competence number, got " + competence.length);
    }

    // rank turkers by competence
    Map<String, Double> turkerIDCompetenceMap = new TreeMap<>();
    for (int i = 0; i < turkerIDs.size(); i++) {
        turkerIDCompetenceMap.put(turkerIDs.get(i), Double.valueOf(competence[i]));
    }

    // sort by value descending
    Map<String, Double> sortedCompetences = IOHelper.sortByValue(turkerIDCompetenceMap, false);
    System.out.println("Sorted turker competences: " + sortedCompetences);

    // assign the gold label and competence

    for (int i = 0; i < allArgumentPairs.size(); i++) {
        AnnotatedArgumentPair annotatedArgumentPair = allArgumentPairs.get(i);
        String goldLabel = predictions.get(i).trim();

        // might be empty
        if (!goldLabel.isEmpty()) {
            // so far the gold label has format aXXX_aYYY_a1, aXXX_aYYY_a2, or aXXX_aYYY_equal
            // strip now only the gold label
            annotatedArgumentPair.setGoldLabel(goldLabel);
        }

        // update turker competence
        for (AnnotatedArgumentPair.MTurkAssignment assignment : annotatedArgumentPair.mTurkAssignments) {
            String turkID = assignment.getTurkID();

            int turkRank = getTurkerRank(turkID, sortedCompetences);
            assignment.setTurkRank(turkRank);

            double turkCompetence = turkerIDCompetenceMap.get(turkID);
            assignment.setTurkCompetence(turkCompetence);
        }
    }

    // now sort the data back according to their original file name
    Map<String, List<AnnotatedArgumentPair>> fileNameAnnotatedPairsMap = new HashMap<>();
    for (AnnotatedArgumentPair argumentPair : allArgumentPairs) {
        String fileName = IOHelper.createFileName(argumentPair.getDebateMetaData(),
                argumentPair.getArg1().getStance());

        if (!fileNameAnnotatedPairsMap.containsKey(fileName)) {
            fileNameAnnotatedPairsMap.put(fileName, new ArrayList<AnnotatedArgumentPair>());
        }

        fileNameAnnotatedPairsMap.get(fileName).add(argumentPair);
    }

    // and save them to the output file
    for (Map.Entry<String, List<AnnotatedArgumentPair>> entry : fileNameAnnotatedPairsMap.entrySet()) {
        String fileName = entry.getKey();
        List<AnnotatedArgumentPair> argumentPairs = entry.getValue();

        File outputFile = new File(outputDir, fileName);

        // and save all sampled pairs into a XML file
        XStreamTools.toXML(argumentPairs, outputFile);

        System.out.println("Saved " + argumentPairs.size() + " pairs to " + outputFile);
    }

}

From source file:br.usp.poli.lta.cereda.macro.Application.java

/**
 * Mtodo principal./*from  ww  w .j a v a2 s  .c o  m*/
 * @param args Argumentos de linha de comando.
 */
public static void main(String[] args) {

    // imprime banner
    System.out.println(StringUtils.repeat("-", 50));
    System.out.println(StringUtils.center("Expansor de macros", 50));
    System.out.println(StringUtils.repeat("-", 50));
    System.out.println(StringUtils.center("Laboratrio de linguagens e tcnicas adaptativas", 50));
    System.out.println(StringUtils.center("Escola Politcnica - Universidade de So Paulo", 50));
    System.out.println();

    try {

        // faz o parsing dos argumentos de linha de comando
        CLIParser parser = new CLIParser(args);
        Pair<String, File> pair = parser.parse();

        // se o par no  nulo,  possvel prosseguir com a expanso
        if (pair != null) {

            // obtm a expanso do texto fornecido na entrada
            String output = MacroExpander.parse(pair.getFirst());

            // se foi definido um arquivo de sada, grava a expanso do
            // texto nele, ou imprime o resultado no terminal, caso
            // contrrio
            if (pair.getSecond() != null) {
                FileUtils.writeStringToFile(pair.getSecond(), output, Charset.forName("UTF-8"));
                System.out.println("Arquivo gerado com sucesso.");
            } else {
                System.out.println(output);
            }

        } else {

            // verifica se a execuo corresponde a uma chamada ao editor
            // embutido de macros
            if (parser.isEditor()) {

                // cria o editor e exibe
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        DisplayUtils.init();
                        Editor editor = new Editor();
                        editor.setVisible(true);
                    }
                });
            }
        }
    } catch (Exception exception) {

        // ocorreu uma exceo, imprime a mensagem de erro
        System.out.println(StringUtils.rightPad("ERRO: ", 50, "-"));
        System.out.println(WordUtils.wrap(exception.getMessage(), 50));
        System.out.println(StringUtils.repeat(".", 50));
    }
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step4BoilerPlateRemoval.java

public static void main(String[] args) throws IOException {
    // input dir - list of xml query containers
    // step3-filled-raw-html
    File inputDir = new File(args[0]);

    // output dir
    File outputDir = new File(args[1]);
    if (!outputDir.exists()) {
        outputDir.mkdirs();// w  w w.j av  a 2  s. c  o m
    }

    // keep original html? (true == default)
    boolean keepOriginalHTML = !(args.length > 2 && "false".equals(args[2]));

    System.out.println(keepOriginalHTML);

    BoilerPlateRemoval boilerPlateRemoval = new JusTextBoilerplateRemoval();

    // iterate over query containers
    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));

        for (QueryResultContainer.SingleRankedResult rankedResults : queryResultContainer.rankedResults) {
            // boilerplate removal

            // there are some empty (corrupted) documents in ClueWeb, namely 0308wb-83.warc.gz
            if (rankedResults.originalHtml != null) {

                rankedResults.plainText = boilerPlateRemoval.getMinimalHtml(rankedResults.originalHtml, null);
            }

            if (!keepOriginalHTML) {
                rankedResults.originalHtml = null;
            }
        }

        // and save the query to output dir
        File outputFile = new File(outputDir, queryResultContainer.qID + ".xml");
        FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8");
        System.out.println("Finished " + outputFile);
    }

}

From source file:edu.cuhk.hccl.TripRealRatingsApp.java

public static void main(String[] args) throws IOException {
    File dir = new File(args[0]);
    File outFile = new File(args[1]);
    outFile.delete();/*from   ww  w  . ja  va2 s  .c o  m*/

    StringBuilder buffer = new StringBuilder();

    for (File file : dir.listFiles()) {
        List<String> lines = FileUtils.readLines(file, "UTF-8");
        String hotelID = file.getName().split("_")[1];
        String author = null;
        boolean noContent = false;
        for (String line : lines) {
            if (line.startsWith("<Author>")) {
                try {
                    author = line.split(">")[1].trim();
                } catch (ArrayIndexOutOfBoundsException e) {
                    System.out.println("[ERROR] An error occured on this line:");
                    System.out.println(line);
                    continue;
                }
            } else if (line.startsWith("<Content>")) { // ignore records if they have no content
                String content = line.split(">")[1].trim();
                if (content == null || content.equals(""))
                    noContent = true;
            } else if (line.startsWith("<Rating>")) {
                String[] rates = line.split(">")[1].trim().split("\t");

                if (noContent || rates.length != 8)
                    continue;

                // Change missing rating from -1 to 0
                for (int i = 0; i < rates.length; i++) {
                    if (rates[i].equals("-1"))
                        rates[i] = "0";
                }

                buffer.append(author + "\t");
                buffer.append(hotelID + "\t");

                // overall
                buffer.append(rates[0] + "\t");
                // location
                buffer.append(rates[3] + "\t");
                // room
                buffer.append(rates[2] + "\t");
                // service
                buffer.append(rates[6] + "\t");
                // value
                buffer.append(rates[1] + "\t");
                // cleanliness
                buffer.append(rates[4] + "\t");

                buffer.append("\n");
            }
        }

        // Write once for each file
        FileUtils.writeStringToFile(outFile, buffer.toString(), true);

        // Clear buffer
        buffer.setLength(0);
        System.out.printf("[INFO] Finished processing %s\n", file.getName());
    }
    System.out.println("[INFO] All processinig are finished!");
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.documents.Step2FillWithRetrievedResults.java

public static void main(String[] args) throws IOException {
    // input dir - list of xml query containers
    File inputDir = new File(args[0]);

    // retrieved results from Technion
    // ltr-50queries-100docs.txt
    File ltr = new File(args[1]);

    // output dir
    File outputDir = new File(args[2]);
    if (!outputDir.exists()) {
        outputDir.mkdirs();//from ww w . ja v a2s . c o  m
    }

    // load the query containers first (into map: id + container)
    Map<String, QueryResultContainer> queryResults = new HashMap<>();
    for (File f : FileUtils.listFiles(inputDir, new String[] { "xml" }, false)) {
        System.out.println(f);
        QueryResultContainer queryResultContainer = QueryResultContainer
                .fromXML(FileUtils.readFileToString(f, "utf-8"));
        queryResults.put(queryResultContainer.qID, queryResultContainer);
    }

    // iterate over IR results
    for (String line : FileUtils.readLines(ltr)) {
        String[] split = line.split("\\s+");
        Integer origQueryId = Integer.valueOf(split[0]);
        String clueWebID = split[2];
        Integer rank = Integer.valueOf(split[3]);
        double score = Double.valueOf(split[4]);
        String additionalInfo = split[5];

        // get the container for this result
        QueryResultContainer container = queryResults.get(origQueryId.toString());

        if (container != null) {
            // add new result
            QueryResultContainer.SingleRankedResult result = new QueryResultContainer.SingleRankedResult();
            result.clueWebID = clueWebID;
            result.rank = rank;
            result.score = score;
            result.additionalInfo = additionalInfo;

            if (container.rankedResults == null) {
                container.rankedResults = new ArrayList<>();
            }
            container.rankedResults.add(result);
        }
    }

    // save all containers to the output dir
    for (QueryResultContainer queryResultContainer : queryResults.values()) {
        File outputFile = new File(outputDir, queryResultContainer.qID + ".xml");
        FileUtils.writeStringToFile(outputFile, queryResultContainer.toXML(), "utf-8");
        System.out.println("Finished " + outputFile);
    }
}