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

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

Introduction

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

Prototype

public static void writeLines(File file, Collection lines) throws IOException 

Source Link

Document

Writes the toString() value of each item in a collection to the specified File line by line.

Usage

From source file:com.gargoylesoftware.htmlunit.source.BrowserVersionFeaturesSource.java

private void rename(final File file, final String oldName, final String newName) throws IOException {
    final List<String> lines = FileUtils.readLines(file);
    boolean modified = false;
    for (int i = 0; i < lines.size(); i++) {
        String line = lines.get(i);
        if (line.equals(oldName) || line.contains(oldName + ")") || line.contains(oldName + ",")) {
            line = line.replace(oldName, newName);
            lines.set(i, line);/*from   w  ww . jav  a2 s . c o m*/
            modified = true;
        }
    }
    if (modified) {
        FileUtils.writeLines(file, lines);
    }
}

From source file:biz.gabrys.lesscss.extended.compiler.storage.DataStorageImpl.java

/**
 * {@inheritDoc}//from  w w  w . ja  v  a  2 s.c  o m
 * @throws DataStorageException if an I/O error occurred.
 * @since 2.0
 */
public void put(final String fileName, final Collection<String> lines) {
    synchronized (mutex) {
        final File cache = getFilePreparedForPut(fileName);
        try {
            FileUtils.writeLines(cache, lines);
        } catch (final IOException e) {
            throw new DataStorageException(e);
        }
    }
}

From source file:es.uvigo.ei.sing.adops.operations.running.codeml.CodeMLDefaultProcessManager.java

@Override
public void createTreeFile(File treeFile, File consFile) throws OperationException {
    try (BufferedReader br = new BufferedReader(new FileReader(consFile))) {
        String line = null;//from  w ww  .j  a  v  a 2 s.c om

        while ((line = br.readLine()) != null && !line.contains("con_50_majrule"))
            ;
        while ((line = br.readLine()) != null && !line.contains("con_50_majrule"))
            ;

        line = line.substring(line.indexOf('('));
        line = line.replaceAll(":[01]\\.[0-9]+", "");

        final int seqCount = line.split(",").length;

        FileUtils.writeLines(treeFile, Arrays.asList(seqCount + " 1\n", line));
    } catch (IOException e) {
        throw new OperationException(null, "Error creating final tree file", e);
    }
}

From source file:com.github.jrh3k5.plugin.maven.l10n.data.AbstractMessagesPropertiesParserTest.java

/**
 * The parsing of duplicate translation keys should tolerate empty lines in the file.
 * //  ww  w  .  ja  v a2 s . c o m
 * @throws Exception
 *             If any errors occur during the test run.
 */
@Test
public void testGetDuplicateTranslationKeysWithEmptyLine() throws Exception {
    final File testFile = getTestFile("messages.properties");
    FileUtils.writeLines(testFile,
            Arrays.asList("emptyline.dup=foo", "emptyline.not.dup=bar", " ", "emptyline.dup=fizzbuzz"));
    assertThat(parser.getDuplicateTranslationKeys(testFile)).hasSize(1).contains("emptyline.dup");
}

From source file:com.opengamma.engine.position.csv.CSVPositionSourceTest.java

private String createTempTestPortfolioDirectory() throws IOException {
    String tempDirName = getTempPortfolioDirectory();
    File tempDir = new File(tempDirName);
    if (!tempDir.mkdir()) {
        throw new IOException(
                "Could not create temporary directory for portfolio files at '" + tempDirName + "'");
    }//from  ww  w.ja  v a2s .c o  m

    Collection<String> testPortfolio1 = new ArrayList<String>();
    testPortfolio1.add("1000,BbgId,APVJS.X Equity");
    testPortfolio1.add("1000,BbgId,APVJS.X Equity");
    testPortfolio1.add("2000,BbgId,APVJN.X Equity");
    testPortfolio1.add("5000,BbgId,AJLJV.X Equity");
    testPortfolio1.add("3500,BbgId,IBMJE.X Equity");
    testPortfolio1.add("450,BbgId,IBMJF.X Equity");
    FileUtils.writeLines(new File(tempDir, "testPortfolio1.csv"), testPortfolio1);

    Collection<String> testPortfolio2 = new ArrayList<String>();
    testPortfolio2.add("120,Domain1,Id1");
    testPortfolio2.add("400,Domain1,Id2");
    testPortfolio2.add("750,Domain2,Id1");
    testPortfolio2.add("1000,Domain3,Id1");
    FileUtils.writeLines(new File(tempDir, "testPortfolio2.port"), testPortfolio2);

    return tempDirName;
}

From source file:com.liferay.ide.gradle.core.GradleProjectBuilder.java

@Override
public IStatus updateProjectDependency(IProject project, List<String[]> dependencies) throws CoreException {
    if (FileUtil.notExists(_gradleBuildFile)) {
        return Status.OK_STATUS;
    }/* w  w  w. j  av  a  2  s.  c  om*/

    try {
        GradleDependencyUpdater updater = new GradleDependencyUpdater(FileUtil.getFile(_gradleBuildFile));

        List<GradleDependency> existDependencies = updater.getAllDependencies();

        for (String[] dependency : dependencies) {
            GradleDependency gd = new GradleDependency(dependency[0], dependency[1], dependency[2]);

            if (!existDependencies.contains(gd)) {
                updater.insertDependency(gd);

                FileUtils.writeLines(_gradleBuildFile.getLocation().toFile(), updater.getGradleFileContents());

                GradleUtil.refreshGradleProject(project);
            }
        }
    } catch (IOException ioe) {
        return GradleCore.createErrorStatus("Error updating gradle project dependency", ioe);
    }

    return Status.OK_STATUS;
}

From source file:gobblin.service.modules.core.IdentityFlowToJobSpecCompilerTest.java

@BeforeClass
public void setup() throws Exception {
    // Create dir for template catalog
    setupDir(TEST_TEMPLATE_CATALOG_PATH);

    // Create template to use in test
    List<String> templateEntries = new ArrayList<>();
    templateEntries.add("testProperty1 = \"testValue1\"");
    templateEntries.add("testProperty2 = \"test.Value1\"");
    templateEntries.add("testProperty3 = 100");
    FileUtils.writeLines(new File(TEST_TEMPLATE_CATALOG_PATH + "/" + TEST_TEMPLATE_NAME), templateEntries);

    // Initialize compiler with template catalog
    Properties compilerWithTemplateCatalogProperties = new Properties();
    compilerWithTemplateCatalogProperties.setProperty(
            ServiceConfigKeys.TEMPLATE_CATALOGS_FULLY_QUALIFIED_PATH_KEY, TEST_TEMPLATE_CATALOG_URI);
    this.compilerWithTemplateCalague = new IdentityFlowToJobSpecCompiler(
            ConfigUtils.propertiesToConfig(compilerWithTemplateCatalogProperties));

    // Add a topology to compiler
    this.compilerWithTemplateCalague.onAddSpec(initTopologySpec());

    // Initialize compiler without template catalog
    this.compilerWithoutTemplateCalague = new IdentityFlowToJobSpecCompiler(
            ConfigUtils.propertiesToConfig(new Properties()));

    // Add a topology to compiler
    this.compilerWithoutTemplateCalague.onAddSpec(initTopologySpec());
}

From source file:de.unisb.cs.st.javalanche.mutation.analyze.TestsTouchedAnalyzer.java

/**
 * The analyze method that is called by the analyzeResults task. This method
 * identifies all the tests that a mutant touched and outputs this pairing
 * to a CSV file./*www  .j  a v a  2s.co m*/
 *
 * @param mutations iterable set of mutations from system under test
 * @param report the HTML report that is being produced (untouched)
 * @return the location that the CSV file was written
 */
public String analyze(Iterable<Mutation> mutations, HtmlReport report) {

    StringBuilder sb = new StringBuilder();
    sb.append("(mutation_id -> tests_touched) pairing located in tests_touched.csv");

    // Build up output for tests touched
    mutantTestTouched.add("MUTANT_ID,TESTS_TOUCHED");
    collectMutantsTestsTouched(mutations);

    // Write collected data to CSV
    try {
        FileUtils.writeLines(new File(
                ConfigurationLocator.getJavalancheConfiguration().getOutputDir() + "/tests_touched.csv"),
                mutantTestTouched);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return sb.toString();
}

From source file:MdDetect.java

/**
 * Create instances of the process function per file
 *
 * @param file the file to process/*from   w w  w. ja v a2s . com*/
 * @return nothing
 */
private static Callable<Void> newProcessFileAction(final File file) {
    return new Callable<Void>() {
        @Override
        public Void call() throws Exception {
            // read the lines of the 'in'-file
            List<String> inLines = FileUtils.readLines(file);

            // queue up the output
            List<String> outLines = new ArrayList<>();

            // flip/flop for blocks
            boolean inBlock = false;

            // line counter
            int ii = 0;
            for (String line : inLines) {
                if (line.matches(MD_CODE_REGEX)) { // is the line the start of a code block?
                    line = line.trim(); // clean it up

                    // flip the block toggle
                    inBlock = !inBlock;

                    if (inBlock && !isAlreadyAnnotated(line)) {
                        // there needs to be a kind of 'look-ahead' here to figure out what tag to use...
                        // lets do a best effort to figure our what it is
                        // how about we grab the next few lines and so some casual checks
                        List<String> codeBlockLines = new ArrayList<>();

                        // grab the rest of this code block
                        grabCodeBlock(inLines, ii, codeBlockLines);

                        // grab the tag to use
                        String tag = supposeLang(codeBlockLines);

                        // then use it
                        line = line.replace("```", "```" + tag);
                    }
                }
                outLines.add(line);
                ii++; // increment the lines counter
            }

            // write the outlines over the old file....
            FileUtils.writeLines(file, outLines);
            return null;
        }
    };
}

From source file:com.mythesis.profileanalysis.Evaluate.java

/**
 * a method tha performs LDA with different parameters and finds the best model using log likelihood estimation
 * @return the directory that contains the parameters of the best model
 *//* w w  w.j  av a  2  s  .co  m*/
public String performLDAevaluation() {

    Metrics met = new Metrics();
    int numOfExperiments = 0;
    double maxLikelihood = 0;
    String maxLikelihoodDir = "";
    System.out.println("I will perform " + beta.size() * nTopics.size() + " experiments...");
    for (int i = 0; i < nTopics.size(); i++) {
        for (int j = 0; j < beta.size(); j++) {
            numOfExperiments++;
            File trainingFile = new File(
                    outputDirectory + "experiments\\" + numOfExperiments + "\\LDAtrain.txt");
            File testFile = new File(outputDirectory + "experiments\\" + numOfExperiments + "\\LDAtest.txt");
            try {
                FileUtils.writeLines(trainingFile, trainingSet);
                FileUtils.writeLines(testFile, testSet);
            } catch (IOException ex) {
                Logger.getLogger(Evaluate.class.getName()).log(Level.SEVERE, null, ex);
            }
            LDAcall ld = new LDAcall();
            ld.call(nTopics.get(i), alpha.get(i), beta.get(j), niters, top_words,
                    outputDirectory + "experiments\\" + numOfExperiments + "\\", true, "LDAtrain.txt");
            ld.call(nTopics.get(i), alpha.get(i), beta.get(j), niters, top_words,
                    outputDirectory + "experiments\\" + numOfExperiments + "\\", false, "LDAtest.txt");
            double likelihood = met.getLogLikelihood(
                    outputDirectory + "experiments\\" + numOfExperiments + "\\", "LDAtest.txt");
            logLikelihoods.add(String.valueOf(likelihood) + "," + String.valueOf(nTopics.get(i)) + ","
                    + String.valueOf(alpha.get(i)) + "," + String.valueOf(beta.get(j)));
            if (numOfExperiments == 1) {
                maxLikelihood = likelihood;
                maxLikelihoodDir = outputDirectory + "experiments\\" + numOfExperiments + "\\";
                bestNoTopics = nTopics.get(i);
                bestBeta = beta.get(j);
            } else if (likelihood > maxLikelihood) {
                maxLikelihood = likelihood;
                maxLikelihoodDir = outputDirectory + "experiments\\" + numOfExperiments + "\\";
                bestNoTopics = nTopics.get(i);
                bestBeta = beta.get(j);
            }
            System.out.println("loglikelihood = " + likelihood);
        }
    }

    File likelihoodsFile = new File(outputDirectory + "experiments\\logLikelihoods.txt");
    try {
        FileUtils.writeLines(likelihoodsFile, logLikelihoods);
    } catch (IOException ex) {
        Logger.getLogger(Evaluate.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println(
            "The best model has loglikelihood = " + maxLikelihood + " and can be found in " + maxLikelihoodDir);
    return maxLikelihoodDir;
}