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:ch.unibas.fittingwizard.application.tools.GaussianLogModifier.java

public File removeHeadersFromCluster(File fileWithHeader) {
    logger.info("Removing headers from cluster from file " + fileWithHeader.getAbsolutePath());

    List<String> lines;
    try {/*ww w . ja va 2 s. c om*/
        lines = FileUtils.readLines(fileWithHeader);
    } catch (IOException e) {
        throw new RuntimeException("Could not read input file " + fileWithHeader.getAbsolutePath());
    }

    int enteringLine = getEnteringLine(lines);
    int terminationLine = getTerminationLine(lines);

    if (enteringLine > 0 && terminationLine > 0 && terminationLine != lines.size() - 1) {
        createBackup(fileWithHeader);
        List<String> linesWithoutHeader = lines.subList(enteringLine, terminationLine + 1);
        try {
            FileUtils.writeLines(fileWithHeader, linesWithoutHeader);
        } catch (IOException e) {
            throw new RuntimeException(
                    "Could not write file without headers. " + fileWithHeader.getAbsolutePath());
        }
    }

    return fileWithHeader;
}

From source file:com.sangupta.codefix.RightTrim.java

protected String processEachFile(File file) throws IOException {
    final List<String> lines = new ArrayList<String>();
    LineIterator iterator = FileUtils.lineIterator(file);
    boolean modified = false;
    while (iterator.hasNext()) {
        String line = iterator.next();

        String newline = StringUtils.stripEnd(line, null);
        if (line.length() != newline.length()) {
            modified = true;/*from w w  w . j a  v a  2  s  .co m*/
        }

        lines.add(newline);
    }

    FileUtils.writeLines(file, lines);
    return String.valueOf(modified);
}

From source file:de.unisb.cs.st.javalanche.mutation.run.task.RandomTaskCreator.java

public static void createTaskRandomSelection(int numberOfMutations, int seed, String fileName)
        throws IOException {
    Random r = new Random(seed);
    Set<Long> coveredSet = MutationCoverageFile.getCoveredMutations();
    List<Long> covered = new ArrayList<Long>(coveredSet);
    Set<Long> selected = new HashSet<Long>();
    List<String> lines = new ArrayList<String>();
    for (int i = 0; i < numberOfMutations && covered.size() > 0; i++) {
        int index = r.nextInt(covered.size());
        Long id = covered.get(index);
        covered.remove(index);//from   www  .  ja  v  a  2  s  . com
        selected.add(id);
        lines.add(id + "");
    }
    // List<Mutation> mutations = QueryManager.getMutationsByIds(selected
    // .toArray(new Long[0]));
    // Collections.sort(mutations);
    File file = new File(fileName);
    FileUtils.writeLines(file, lines);

}

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

/**
 * Ensures that all files inside the specified directory has consistent new lines.
 * @param dir the directory to recursively ensure all contained files have consistent new lines
 * @throws IOException if an exception happens
 *///from ww w.jav  a  2s .  c  om
public static void consistentNewlines(final File dir) throws IOException {
    for (final File f : dir.listFiles()) {
        if (f.isDirectory()) {
            if (!".svn".equals(f.getName())) {
                consistentNewlines(f);
            }
        } else {
            final String fileName = f.getName().toLowerCase(Locale.ROOT);
            for (final String extension : EOL_EXTENSIONS_) {
                if (fileName.endsWith(extension)) {
                    FileUtils.writeLines(f, FileUtils.readLines(f));
                    break;
                }
            }
        }
    }
}

From source file:com.ms.commons.test.tool.util.AutoDeleteProjectTaskUtil.java

public static Task wrapAutoDeleteTask(final File project, final Task oldTask) {

    String userDir = System.getProperty("user.dir");

    List<Element> projectElements = ClassPathAccessor.getElementsByXPath(project, "/project");
    if ((projectElements == null) || (projectElements.size() != 1)) {
        System.err.println("File '" + project + "' format error!");
        System.exit(-1);/* w  w  w  .  ja v  a2s  .  c  o m*/
    }
    final String projectId = projectElements.get(0).getAttributeValue("id");
    final String projectExtends = projectElements.get(0).getAttributeValue("extends");

    System.out.println("Project id:" + projectId);
    System.out.println("Project extends:" + projectExtends);

    final File baseProject = new File(userDir + File.separator + projectExtends);
    if (!baseProject.exists()) {
        System.err.println("Base file '" + baseProject + "' not found!");
        System.exit(-1);
    }

    List<Element> findProjectIdElements = ClassPathAccessor.getElementsByXPath(baseProject,
            "/project/projects/project[@id='" + projectId + "']");

    if ((findProjectIdElements != null) && (findProjectIdElements.size() > 0)) {
        System.out.println("Find project id in base project file.");
        return new Task() {

            @SuppressWarnings("unchecked")
            public void finish() {
                boolean hasError = false;
                File backUpFile = new File(baseProject.getAbsoluteFile() + ".backup");
                try {
                    FileUtils.copyFile(baseProject, backUpFile);

                    // XMLAPI
                    List<String> outLines = new ArrayList<String>();
                    List<String> lines = FileUtils.readLines(baseProject);
                    for (String line : lines) {
                        if (!(line.contains("\"" + projectId + "\""))) {
                            outLines.add(line);
                        }
                    }
                    FileUtils.writeLines(baseProject, outLines);

                    oldTask.finish();
                } catch (Exception e) {
                    hasError = true;
                    e.printStackTrace();
                } finally {
                    baseProject.delete();
                    try {
                        FileUtils.copyFile(backUpFile, baseProject);
                    } catch (IOException e) {
                        hasError = true;
                        e.printStackTrace();
                    }
                    backUpFile.delete();
                }
                if (hasError) {
                    System.exit(-1);
                }
            }
        };
    } else {
        System.out.println("Not find project id in base project file.");
    }

    return oldTask;
}

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

@Override
public String analyze(Iterable<Mutation> mutations, HtmlReport report) {

    List<String> lines = new ArrayList<String>();
    lines.add(Mutation.getCsvHead() + ",Covered, Detected");
    for (Mutation mutation : mutations) {
        MutationTestResult result = mutation.getMutationResult();
        boolean covered = false;
        if (result != null) {
            covered = result.isTouched();
        }/*w w  w . ja v a2s  .  c  om*/
        lines.add(mutation.getCsvString() + "," + covered + "," + mutation.isDetected());

    }
    // File outputDir = ConfigurationLocator.getJavalancheConfiguration()
    // .getOutputDir();
    int entries = (lines.size() - 1);
    String fileName = "mutations-" + entries + ".csv";
    File outFile = new File(fileName);
    try {
        FileUtils.writeLines(outFile, lines);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return String.format("File with %d entries written (%s) ", entries, outFile.getAbsolutePath());
}

From source file:azkaban.app.AzkabanApplicationTest.java

@Test
public void testAddJobAndReload() throws Exception {
    String testJob = "testjob";
    AzkabanApplication app = new AzkabanApplication(Arrays.asList(jobDir), logDir, tmpDir, false);
    Assert.assertEquals(0, app.getJobManager().loadJobDescriptors().size());
    Assert.assertNull(app.getJobManager().getJobDescriptor(testJob));

    File newJobDir = new File(jobDir, "test");
    FileUtils.forceMkdir(newJobDir);//from   w w  w. j a v a 2s.  co m
    File newJob = new File(newJobDir, testJob + ".job");
    FileUtils.writeLines(newJob, Arrays.asList("type=command", "command=ls"));

    app.reloadJobsFromDisk();

    Assert.assertEquals(1, app.getJobManager().loadJobDescriptors().size());
    Job loadedJob = app.getJobManager().loadJob(testJob, true);

    Assert.assertEquals(testJob, loadedJob.getId());
    Assert.assertTrue(loadedJob instanceof LoggingJob);
    Assert.assertTrue(((LoggingJob) loadedJob).getInnerJob() instanceof ProcessJob);
}

From source file:gov.nih.nci.caarray.magetab.splitter.SdrfSplitter.java

/**
 * Creates a small sdrf file which contains only rows that reference the given data file.
 * This method also tracks and updates which rows of the original sdrf are still unused.
 * // w w w.  ja v a 2  s  . com
 * @param dataFile data file to find references to in the sdrf
 * @return small sdrf that has all rows that reference dataFile
 * @throws IOException if writing to new files fails or any other io error
 */
public FileRef splitByDataFile(FileRef dataFile) throws IOException {
    List<String> outputLines = new ArrayList<String>();
    String dataFileName = dataFile.getName().toLowerCase(Locale.getDefault());
    for (String curLine : lines) {
        if (outputLines.isEmpty()) {
            // Add the header line.
            outputLines.add(curLine);
        }
        if (curLine.toLowerCase(Locale.getDefault()).indexOf(dataFileName) >= 0) {
            // Add any lines that reference this data file.
            outputLines.add(curLine);
            unusedLines.remove(curLine);
        }
    }
    File outputFile = File.createTempFile(file.getName(), ".sdrf");
    FileUtils.writeLines(outputFile, outputLines);
    return new JavaIOFileRef(outputFile);
}

From source file:end2endtests.runner.ServerRunner.java

private void createAppConfig(Class<?> application) throws IOException {
    File configFile = new File(applicationDir, "classes/META-INF/app.properties");
    FileUtils.writeLines(configFile, Arrays.asList("dimdwarf.app.name=" + application.getSimpleName(),
            "dimdwarf.app.module=" + application.getName()));
}

From source file:com.sangupta.clitools.file.Trim.java

@Override
protected boolean processFile(File file) throws IOException {
    // read entire file in memory
    List<String> contents = FileUtils.readLines(file);
    final long initial = file.length();

    // now for each string - trim from end
    for (int index = 0; index < contents.size(); index++) {
        String line = contents.get(index);
        line = StringUtils.strip(line, null);
        contents.set(index, line);//w w  w.  ja v  a  2 s  .  c o m
    }

    // write back contents of file
    FileUtils.writeLines(file, contents);
    long current = file.length();

    this.bytesSaved.addAndGet(initial - current);
    System.out.println("File " + file.getAbsoluteFile().getAbsolutePath() + " trimmed and saved "
            + (initial - current) + " bytes.");
    return true;
}