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:cz.cas.lib.proarc.common.process.GenericExternalProcessTest.java

/** onExit is an experimental feature .*/
@Test/*from  ww w  .  j a  v a  2s  .  co  m*/
public void testIMConvertOnExit() throws Exception {
    String imageMagicExec = "/usr/bin/convert";
    Assume.assumeTrue(new File(imageMagicExec).exists());
    File confFile = temp.newFile("props.cfg");
    File root = temp.getRoot();
    URL pdfaResource = TiffImporterTest.class.getResource("pdfa_test.pdf");
    File pdfa = new File(root, "pdfa_test.pdf");
    FileUtils.copyURLToFile(pdfaResource, pdfa);
    FileUtils.writeLines(confFile,
            Arrays.asList("input.file.name=RESOLVED", "exec=" + imageMagicExec, "arg=-thumbnail", "arg=120x128",
                    "arg=$${input.file}[0]", "arg=-flatten", "arg=$${input.folder}/$${input.file.name}.jpg",
                    "result.file=$${input.folder}/$${input.file.name}.jpg", "onExits=0",
                    "onExit.0.param.output.file=$${input.folder}/$${input.file.name}.jpg", "id=test"));
    PropertiesConfiguration conf = new PropertiesConfiguration(confFile);
    GenericExternalProcess gep = new GenericExternalProcess(conf);
    gep.addInputFile(pdfa);
    gep.run();
    //        System.out.printf("#exit: %s, out: %s\nresults: %s\n",
    //                gep.getExitCode(), gep.getFullOutput(), gep.getResultParameters());
    assertEquals("exit code", 0, gep.getExitCode());
    File output = gep.getOutputFile();
    assertNotNull(output);
    assertTrue(output.toString(), output.exists());
    assertTrue("Not JPEG", InputUtils.isJpeg(output));
}

From source file:jp.igapyon.selecrawler.SeleCrawlerWebContentNewUrlFinder.java

public void process(final SeleCrawlerSettings settings) throws IOException {
    this.settings = settings;
    System.err.println("[jp.igapyon.selecrawler] Find new url from fetched contents.");

    final List<String> urlList = new ArrayList<String>();
    processGatherUrl(urlList);/*from w  ww.  j  av a2s .c o m*/

    Collections.sort(urlList);
    // remove duplicated urls
    for (int index = 1; index < urlList.size(); index++) {
        if (urlList.get(index - 1).equals(urlList.get(index))) {
            urlList.remove(index--);
        }
    }

    // remove if already registered.
    {
        final List<String> registeredList = FileUtils.readLines(new File(settings.getPathUrllisttTxt()),
                "UTF-8");
        final Map<String, String> registeredMap = new HashMap<String, String>();
        for (String urlRegistered : registeredList) {
            registeredMap.put(urlRegistered, urlRegistered);
        }
        for (int index = 0; index < urlList.size(); index++) {
            if (registeredMap.get(urlList.get(index)) != null) {
                // remove registered url.
                urlList.remove(index--);
            }
        }
    }

    // remove it if it is marked as exclude
    for (int index = 0; index < urlList.size(); index++) {
        final String url = urlList.get(index);
        final List<String> excludeRegexList = FileUtils
                .readLines(new File(settings.getPathUrllistExcludeRegexTxt()), "UTF-8");
        for (String regex : excludeRegexList) {
            final Pattern pat = Pattern.compile(regex);
            final Matcher mat = pat.matcher(url);

            if (mat.find()) {
                // remove registered url.
                urlList.remove(index--);
            }
        }
    }

    final File newurlcandidate = new File(new File(settings.getPathTargetDir()),
            SeleCrawlerConstants.EXT_SC_NEWURLCANDIDATE);
    System.err.println(
            "[selecrawler] create/update new url candidate file: " + newurlcandidate.getCanonicalPath());
    FileUtils.writeLines(newurlcandidate, urlList);
}

From source file:edu.ku.brc.specify.dbsupport.cleanuptools.FirstLastVerifier.java

/**
 * @param args/*w ww. j  a va  2  s  . com*/
 */
public static void main(String[] args) {
    if (true) {
        testLastNames();
        return;
    }
    FirstLastVerifier flv = new FirstLastVerifier();
    System.out.println(flv.isFirstName("Bill"));
    System.out.println(flv.isLastName("Bill"));

    System.out.println(flv.isFirstName("Johnson"));
    System.out.println(flv.isLastName("Johnson"));

    try {
        if (false) {
            for (String nm : new String[] { "firstnames", "lastnames" }) {
                File file = new File("/Users/rods/Downloads/" + nm + ".txt");
                try {
                    PrintWriter pw = new PrintWriter("/Users/rods/Downloads/" + nm + ".list");
                    for (String line : (List<String>) FileUtils.readLines(file)) {
                        String[] toks = StringUtils.split(line, '\t');
                        if (toks != null && toks.length > 0)
                            pw.println(toks[0]);
                    }
                    pw.close();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        Vector<String> lnames = new Vector<String>();
        File file = XMLHelper.getConfigDir("lastnames.list");
        if (false) {
            for (String name : (List<String>) FileUtils.readLines(file)) {
                if (flv.isFirstName(name)) {
                    System.out.println(name + " is first.");
                } else {
                    lnames.add(name);
                }
            }
            Collections.sort(lnames);
            FileUtils.writeLines(file, lnames);
        }

        lnames.clear();
        file = XMLHelper.getConfigDir("firstnames.list");
        for (String name : (List<String>) FileUtils.readLines(file)) {
            if (flv.isLastName(name)) {
                System.out.println(name + " is first.");
            } else {
                lnames.add(name);
            }
        }
        Collections.sort(lnames);
        //FileUtils.writeLines(file, lnames);

    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:edu.ku.brc.util.HelpIndexer.java

/**
 * //w ww.j  av  a  2s .c  o  m
 */
@SuppressWarnings("unchecked")
public void indexIt() {
    if (!jhm.exists()) {
        System.out.println("jhm file not found.");
        return;
    }
    if (!topDir.isDirectory()) {
        System.out.println("directory does not exist.");
        return;
    }
    try {
        mapLines = FileUtils.readLines(jhm);
    } catch (IOException ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(HelpIndexer.class, ex);
        System.out.println("Error reading map file: " + ex.getMessage());
        return;
    }

    Vector<String> lines = new Vector<String>();
    String[] ext = { "html" };
    Iterator<File> helpFiles = FileUtils.iterateFiles(topDir, ext, true);
    while (helpFiles.hasNext()) {
        File file = helpFiles.next();
        System.out.println("Processing " + file.getName());
        processFile(file, lines);
    }

    System.out.println();
    System.out.println("all done.");

    File outFile = new File(outFileName);
    try {

        //add lines to top of file
        lines.insertElementAt("<?xml version='1.0' encoding='ISO-8859-1'  ?>", 0);
        lines.insertElementAt("<!DOCTYPE index", 1);
        lines.insertElementAt("  PUBLIC \"-//Sun Microsystems Inc.//DTD JavaHelp Index Version 1.0//EN\"", 2);
        lines.insertElementAt("         \"http://java.sun.com/products/javahelp/index_1_0.dtd\">", 3);
        lines.insertElementAt("<index version=\"1.0\">", 4);
        lines.insertElementAt(" ", 5);

        //and bottom...
        lines.add(" ");
        lines.add("</index>");

        FileUtils.writeLines(outFile, lines);
    } catch (IOException ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(HelpIndexer.class, ex);
        System.out.println("error writing output file: " + ex.getMessage());
    }
}

From source file:com.github.aliakhtar.annoTest.util.Compiler.java

protected File writeSourceFile(SourceFile sourceFile) throws IOException {
    File file = new File(sourceDir, sourceFile.getFileName());
    FileUtils.writeLines(file, sourceFile.getContent());
    return file;//  w  ww .j  a  va 2s.  co m
}

From source file:io.seqware.pipeline.whitestar.WhiteStarTest.java

protected static Path createSettingsFile(String engine, String metadataMethod) throws IOException {
    // override seqware settings file
    List<String> whiteStarProperties = new ArrayList<>();
    whiteStarProperties.add("SW_METADATA_METHOD=" + metadataMethod);
    whiteStarProperties.add("SW_REST_USER=admin@admin.com");
    whiteStarProperties.add("SW_REST_PASS=admin");
    whiteStarProperties.add("SW_ADMIN_REST_URL=fubar");
    whiteStarProperties.add("SW_DEFAULT_WORKFLOW_ENGINE=" + engine);
    whiteStarProperties.add("OOZIE_WORK_DIR=/tmp");
    // use this if running locally via mvn tomcat7:run
    // whiteStarProperties.add("SW_REST_URL=http://localhost:8889/seqware-webservice");
    // use this in our regression testing framework
    whiteStarProperties.add("SW_REST_URL=http://master:8080/SeqWareWebService");
    Path createTempFile = Files.createTempFile("whitestar", "properties");
    FileUtils.writeLines(createTempFile.toFile(), whiteStarProperties);
    return createTempFile;
}

From source file:com.thesmartweb.swebrank.Sensebot.java

/**
 * Method to get the top sensebot concepts recognized for given links
 * @param links the links to search for//w  w w.java 2 s . c o m
 * @param directory the directory to save the results to
 * @param SensebotConcepts the amount of concepts to search for
 * @param config_path the path to find sensebot's username
 * @return a list with all the top sensebot concepts recognized for the given links
 */
public List<String> compute(String[] links, String directory, int SensebotConcepts, String config_path) {
    List<String> wordList = new ArrayList<>();
    try {
        URL diff_url = null;
        String stringtosplit = "";
        String username = GetUserName(config_path);
        for (String link : links) {
            if (!(link == null)) {
                diff_url = new URL("http://api.sensebot.net/svc/extconcone.asmx/ExtractConcepts?userName="
                        + username + "&numConcepts=" + SensebotConcepts
                        + "&artClass=&artLength=0&Lang=English&allURLs=" + link);
                stringtosplit = connect(diff_url);
                if (!(stringtosplit == null) && (!(stringtosplit.equalsIgnoreCase("")))) {
                    stringtosplit = stringtosplit.replaceAll("[\\W&&[^\\s]]", "");
                    if (!(stringtosplit == null) && (!(stringtosplit.equalsIgnoreCase("")))) {
                        String[] tokenizedTerms = stringtosplit.split("\\W+"); //to get individual terms
                        for (String tokenizedTerm : tokenizedTerms) {
                            if (!(tokenizedTerm == null) && (!(tokenizedTerm.equalsIgnoreCase("")))) {
                                wordList.add(tokenizedTerm);
                            }
                        }
                    }
                }
            }
        }
        File file_words = new File(directory + "words.txt");
        FileUtils.writeLines(file_words, wordList);
        return wordList;
    } catch (MalformedURLException ex) {
        Logger.getLogger(Diffbot.class.getName()).log(Level.SEVERE, null, ex);
        return wordList;
    } catch (IOException ex) {
        Logger.getLogger(Diffbot.class.getName()).log(Level.SEVERE, null, ex);
        return wordList;
    }
}

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

/**
 * a method that cleans the word vector of a certain sub-domain
 * @param directory the directory where im gonna save the results
 * @param profile the profile i want to get the wordvector 
 * @param master the general domain/*from w  ww  . j av  a2  s. c o  m*/
 */
public void cleanWordVector(String directory, String profile, String master) {

    List<String> masterVector = new ArrayList<>();
    List<String> wordVector = new ArrayList<>();
    File wordsFile;
    try {
        wordsFile = new File(directory + "\\wordVector" + master + ".txt");
        masterVector = FileUtils.readLines(wordsFile); // get the word vector of the general domain
        wordsFile = new File(directory + "\\wordVector" + profile + ".txt");
        wordVector = FileUtils.readLines(wordsFile); // get the word vector of the sub-domain
    } catch (IOException ex) {
        Logger.getLogger(WordVectorFinder.class.getName()).log(Level.SEVERE, null, ex);
    }

    for (String s : masterVector) {
        if (wordVector.contains(s))
            wordVector.remove(s); // remove any word that occurs in general domain's word vector
    }

    // save the new word vector
    File wordVectorPath = new File(directory + "\\wordVectorCleaned" + profile + ".txt");
    try {
        FileUtils.writeLines(wordVectorPath, wordVector);
    } catch (IOException ex) {
        Logger.getLogger(WordVectorFinder.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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

public String analyze(Iterable<Mutation> mutations, HtmlReport report) {
    int touched = 0;
    int notTouched = 0;
    List<Mutation> killedList = new ArrayList<Mutation>();
    List<Mutation> survivedList = new ArrayList<Mutation>();
    List<Mutation> survivedTouchedList = new ArrayList<Mutation>();
    List<Long> notCovered = new ArrayList<Long>();
    int covered = 0;
    for (Mutation mutation : mutations) {
        if (mutation == null) {
            throw new RuntimeException("Null fetched from db");
        }//from   ww  w .ja  v  a2 s  .  c om
        MutationTestResult mutationResult = mutation.getMutationResult();
        boolean mutationTouched = mutationResult != null && mutationResult.isTouched();
        if (mutation.isDetected()) {
            killedList.add(mutation);
        } else {
            survivedList.add(mutation);
            if (mutationTouched) {
                survivedTouchedList.add(mutation);
            }
        }
        if (mutationTouched) {
            touched++;
        } else {
            notTouched++;
        }
        boolean isCovered = MutationCoverageFile.isCovered(mutation.getId());
        boolean isDerived = mutation.getBaseMutationId() != null;
        String info = mutation.getMutationType() + " Derived " + isDerived + "  " + mutation.toShortString()
                + " " + mutation.getAddInfo() + " " + mutation.getOperatorAddInfo();
        if (isCovered != mutationTouched) {
            String message;
            if (isCovered) {
                message = "Mutation is considered to be covered by tests, but was actually not executed during mutation testing.";
            } else {
                message = "Mutation was not considered to be covered by tests, but was actually executed during mutation testing.";
            }
            logger.warn(message + "  " + info);
            notCovered.add(mutation.getId());
        }
        if (isCovered) {
            covered++;
        }
    }
    int killed = killedList.size();
    int survived = survivedList.size();
    int total = survived + killed;
    assert (survived + killed) == (notTouched + touched);
    StringBuilder sb = new StringBuilder();

    Set<Long> killedIds = new TreeSet<Long>();
    Set<Long> survivedIds = new TreeSet<Long>();
    for (Mutation mutation : killedList) {
        killedIds.add(mutation.getId());
    }
    for (Mutation mutation : survivedTouchedList) {
        survivedIds.add(mutation.getId());
    }
    try {
        FileUtils.writeLines(new File(ConfigurationLocator.getJavalancheConfiguration().getOutputDir()
                + "/not-covered-during-mutation-testing-id.txt"), notCovered);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    if (WRITE_FILES) {
        XmlIo.toXML(killedList, "killed-mutations.xml");
        XmlIo.toXML(survivedList, "survived-mutations.xml");
        XmlIo.toXML(killedIds, "killed-ids.xml");
        XmlIo.toXML(survivedIds, "survived-ids.xml");
    }
    sb.append(formatLine("Total mutations:  ", total));
    sb.append(formatLine("Covered mutations (in scan step): ", covered,
            AnalyzeUtil.formatPercent(covered, total)));
    sb.append(formatLine("Covered mutations (actually executed during mutation testing): ", touched,
            AnalyzeUtil.formatPercent(touched, total)));
    sb.append(formatLine("Not covered mutations: ", notTouched, AnalyzeUtil.formatPercent(notTouched, total)));
    sb.append(formatLine("Killed mutations: ", killed, AnalyzeUtil.formatPercent(killed, total)));
    sb.append(formatLine("Surviving mutations: ", survived, AnalyzeUtil.formatPercent(survived, total)));
    // sb.append("IDs:\n");
    // for (Long survivedId : survivedIds) {
    // sb.append(survivedId).append(", ");
    // }
    sb.append(formatLine("Mutation score: ", AnalyzeUtil.formatPercent(killed, total)));
    sb.append(formatLine("Mutation score for mutations that were covered: ",
            AnalyzeUtil.formatPercent(killed, touched)));
    if (notCovered.size() > 0) {
        sb.append(formatLine("Mutations that where expected to be covered but actually not covered: ",
                notCovered.size(), notCovered.toString()));
    }
    return sb.toString();
}

From source file:io.github.bunnyblue.droidfix.classcomputer.proguard.MappingMapper.java

public void writeNewClassCache(ArrayList<ClassObject> cacheClasses) {

    Collections.sort(cacheClasses);
    ArrayList<String> md5s = new ArrayList<String>();

    for (ClassObject classObject : cacheClasses) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(classObject.getClassName());
        stringBuffer.append(" ");
        stringBuffer.append(classObject.getMd5());
        md5s.add(stringBuffer.toString());

    }//from  w ww  .j  a va 2s  .  co m
    try {
        FileUtils.writeLines(new File(Configure.getInstance().getPatchClassMD5()), md5s);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}