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

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

Introduction

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

Prototype

public static List readLines(File file) throws IOException 

Source Link

Document

Reads the contents of a file line by line to a List of Strings using the default encoding for the VM.

Usage

From source file:ch.bender.evacuate.EvacuateMain.java

/**
 * initExcludePattersFromFile/*from ww w  .  jav  a2  s .c om*/
 * <p>
 * @param aFilename
 * @return
 */
private List<String> initExcludePattersFromFile(String aFilename) {
    List<String> result = new ArrayList<>();

    Path path = Paths.get(aFilename);

    if (Files.notExists(path)) {
        throw new IllegalArgumentException("File " + aFilename + " does not exist");
    }

    try {
        result = FileUtils.readLines(path.toFile());
    } catch (IOException e) {
        throw new IllegalArgumentException("File " + aFilename + " cannot be read", e);
    }

    return result;

}

From source file:com.legstar.jaxb.gen.CobolJAXBGenerator.java

/**
 * Checks that properties set are valid.
 *//*  w w w . j  a  va2  s  .  c  o m*/
protected void checkInput() {

    try {
        if (_log.isDebugEnabled()) {
            _log.debug("checkInput started");
            _log.debug("Schema: " + getXsdFile());
            _log.debug("TargetDir: " + getTargetDir());
            _log.debug("Package name: " + getJaxbPackageName());
            _log.debug("xjbModel: " + _context);
        }
        if (getXsdFile() == null) {
            throw (new BuildException("You must specify an XML schema file name"));
        } else {
            if (getXsdFile().exists()) {
                if (_log.isDebugEnabled()) {
                    for (Object line : FileUtils.readLines(getXsdFile())) {
                        _log.debug(line);
                    }
                }
            } else {
                throw (new BuildException(
                        "XML schema file " + getXsdFile().getAbsolutePath() + " does not exist"));
            }
        }
        if (getTargetDir() == null) {
            throw (new BuildException("You must specify a destination directory"));
        }
    } catch (IOException e) {
        throw new BuildException(e);
    }
}

From source file:gov.va.chir.tagline.dao.FileDao.java

public static Collection<Document> loadLabeledLines(final File file, boolean hasHeader) throws IOException {
    final Map<String, Map<Integer, Line>> docMap = new HashMap<String, Map<Integer, Line>>();

    // Assumes tab-delimited columns. May not be sorted.
    // Column labels may be on first line
    // Col 0 = NoteID
    // Col 1 = LineID
    // Col 2 = Class
    // Col 3 = Text
    final int POS_DOC_ID = 0;
    final int POS_LINE_ID = 1;
    final int POS_CLASS = 2;
    final int POS_TEXT = 3;

    final List<String> contents = FileUtils.readLines(file);

    for (int i = (hasHeader ? 1 : 0); i < contents.size(); i++) {
        final String l = contents.get(i);
        final String[] array = l.split("\t");

        if (!docMap.containsKey(array[POS_DOC_ID])) {
            docMap.put(array[POS_DOC_ID], new TreeMap<Integer, Line>());
        }//from   w  w w . j a  v  a  2s.com

        int lineId = NumberUtils.toInt(array[POS_LINE_ID]);

        final Line line = new Line(lineId, (array.length == POS_TEXT ? "" : array[POS_TEXT]), // blank lines have no content 
                array[POS_CLASS]);

        docMap.get(array[POS_DOC_ID]).put(lineId, line);
    }

    final Collection<Document> docs = new ArrayList<Document>();

    for (String docId : docMap.keySet()) {
        docs.add(new Document(docId, new ArrayList<Line>(docMap.get(docId).values())));
    }

    return docs;
}

From source file:de.unisb.cs.st.javalanche.mutation.util.ResultDeleter.java

private static void deleteResultsFromFile(File f) throws IOException {
    List<String> readLines = FileUtils.readLines(f);
    List<Long> ids = new ArrayList<Long>();
    for (String idString : readLines) {
        ids.add(Long.valueOf(idString));
    }//ww  w  .  jav  a2 s  .  c  o m
    deleteMutationResults(ids);
}

From source file:com.sojw.TableNamesFinderExecutor.java

public static List<String> getFileContents(final String filePath) throws IOException {
    final List<String> fileContentList = FileUtils.readLines(FileUtils.getFile(filePath));
    return fileContentList;
}

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

private void specificationSdrfWithTransform(Function<File, File> transform) throws IOException {
    File transformed = transform == null ? sdrf : transform.apply(sdrf);
    FileRef fileRef = new JavaIOFileRef(transformed);

    SdrfSplitter splitter = new SdrfSplitter(fileRef);
    FileRef splitSdrf = splitter.splitByDataFile(dataFile1);

    @SuppressWarnings("unchecked")
    List<String> splitLines = FileUtils.readLines(splitSdrf.getAsFile());
    assertEquals(dataFile1References + 1, splitLines.size());
    assertEquals(sdrfLines.get(0), splitLines.get(0));
}

From source file:de.tudarmstadt.ukp.dkpro.core.textnormalizer.ReplacementFileNormalizer.java

private Map<String, String> getReplacementMap() throws ResourceInitializationException {
    Map<String, String> replacementMap = new HashMap<String, String>();
    try {/*  w  ww . j  a v  a2 s. com*/
        // Reads in all mappings of expressions(to be replaced expression, target expression)
        // and fills replacement map
        for (String line : FileUtils.readLines(new File(replacePath))) {
            if (!line.isEmpty()) {
                // Each line of source file contains mapping of "to replaced expression" and the
                // "target expressions"
                // those expressions are separated by tabs
                String[] entry = line.split("\t");
                replacementMap.put(entry[0], entry[1]);
            }
        }
    } catch (IOException e) {
        throw new ResourceInitializationException(e);
    }

    return replacementMap;
}

From source file:edu.ku.brc.specify.tools.LocalizerSearchHelper.java

/**
 * @param baseDir/*from   ww w .  ja  v a 2 s.  co  m*/
 * @return
 */
public Vector<Pair<String, String>> findOldL10NKeys(final String[] fileNames) {
    initLucene(true);

    //if (srcCodeFilesDir == null)
    {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (srcCodeFilesDir != null) {
            chooser.setSelectedFile(new File(FilenameUtils.getName(srcCodeFilesDir.getAbsolutePath())));
            chooser.setSelectedFile(new File(srcCodeFilesDir.getParent()));
        }

        if (chooser.showOpenDialog(UIRegistry.getMostRecentWindow()) == JFileChooser.APPROVE_OPTION) {
            srcCodeFilesDir = new File(chooser.getSelectedFile().getAbsolutePath());
        } else {
            return null;
        }
    }

    indexSourceFiles();

    Vector<Pair<String, String>> fullNotFoundList = new Vector<Pair<String, String>>();

    try {
        ConversionLogger convLogger = new ConversionLogger();
        convLogger.initialize("resources", "Resources");

        for (String fileName : fileNames) {
            Vector<Pair<String, String>> notFoundList = new Vector<Pair<String, String>>();

            Vector<String> terms = new Vector<String>();

            String propFileName = baseDir.getAbsolutePath() + "/" + fileName;

            File resFile = new File(propFileName + ".properties");
            if (resFile.exists()) {
                List<?> lines = FileUtils.readLines(resFile);
                for (String line : (List<String>) lines) {
                    if (!line.startsWith("#")) {
                        int inx = line.indexOf("=");
                        if (inx > -1) {
                            String[] toks = StringUtils.split(line, "=");
                            if (toks.length > 1) {
                                terms.add(toks[0]);
                            }
                        }
                    }
                }
            } else {
                System.err.println("Doesn't exist: " + resFile.getAbsolutePath());
            }

            String field = "contents";
            QueryParser parser = new QueryParser(Version.LUCENE_36, field, analyzer);

            for (String term : terms) {
                Query query;
                try {
                    if (term.equals("AND") || term.equals("OR"))
                        continue;

                    query = parser.parse(term);

                    String subTerm = null;
                    int hits = getTotalHits(query, 10);
                    if (hits == 0) {
                        int inx = term.indexOf('.');
                        if (inx > -1) {
                            subTerm = term.substring(inx + 1);
                            hits = getTotalHits(parser.parse(subTerm), 10);

                            if (hits == 0) {
                                int lastInx = term.lastIndexOf('.');
                                if (lastInx > -1 && lastInx != inx) {
                                    subTerm = term.substring(lastInx + 1);
                                    hits = getTotalHits(parser.parse(subTerm), 10);
                                }
                            }
                        }
                    }

                    if (hits == 0 && !term.endsWith("_desc")) {
                        notFoundList.add(new Pair<String, String>(term, subTerm));

                        log.debug("'" + term + "' was not found "
                                + (subTerm != null ? ("SubTerm[" + subTerm + "]") : ""));
                    }

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

            String fullName = propFileName + ".html";
            TableWriter tblWriter = convLogger.getWriter(FilenameUtils.getName(fullName), propFileName);
            tblWriter.startTable();
            tblWriter.logHdr("Id", "Full Key", "Sub Key");
            int cnt = 1;
            for (Pair<String, String> pair : notFoundList) {
                tblWriter.log(Integer.toString(cnt++), pair.first,
                        pair.second != null ? pair.second : "&nbsp;");
            }
            tblWriter.endTable();

            fullNotFoundList.addAll(notFoundList);

            if (notFoundList.size() > 0 && resFile.exists()) {
                List<String> lines = (List<String>) FileUtils.readLines(resFile);
                Vector<String> linesCache = new Vector<String>();

                for (Pair<String, String> p : notFoundList) {
                    linesCache.clear();
                    linesCache.addAll(lines);

                    int lineInx = 0;
                    for (String line : linesCache) {
                        if (!line.startsWith("#")) {
                            int inx = line.indexOf("=");
                            if (inx > -1) {
                                String[] toks = StringUtils.split(line, "=");
                                if (toks.length > 1) {
                                    if (toks[0].equals(p.first)) {
                                        lines.remove(lineInx);
                                        break;
                                    }
                                }
                            }
                        }
                        lineInx++;
                    }
                }
                FileUtils.writeLines(resFile, linesCache);
            }

        }
        convLogger.closeAll();

    } catch (IOException ex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(LocalizerSearchHelper.class, ex);
        ex.printStackTrace();
    }

    return fullNotFoundList;
}

From source file:de.tudarmstadt.ukp.dkpro.tc.svmhmm.util.SVMHMMUtils.java

/**
 * Extracts the outcome labels from the file; it corresponds to the first token
 * on each line.//from w  ww .  j a va 2  s  .c o m
 *
 * @param featureVectorsFile featureVectors file
 * @return list of outcome labels
 * @throws IOException
 */
public static List<String> extractOutcomeLabels(File featureVectorsFile) throws IOException {
    List<String> result = new ArrayList<>();
    List<String> lines = FileUtils.readLines(featureVectorsFile);
    for (String line : lines) {
        String label = line.split("\\s")[0];

        result.add(label);
    }
    return result;
}

From source file:com.mirth.connect.server.controllers.DefaultExtensionController.java

@Override
public void removePropertiesForUninstalledExtensions() {
    try {/*  www.  jav a  2  s  .c  om*/
        File uninstallFile = new File(getExtensionsPath(), EXTENSIONS_UNINSTALL_PROPERTIES_FILE);

        if (uninstallFile.exists()) {
            List<String> extensionPaths = FileUtils.readLines(uninstallFile);

            for (String extensionPath : extensionPaths) {
                configurationController.removePropertiesForGroup(extensionPath);
            }

            // delete the uninstall file when we're done
            FileUtils.deleteQuietly(uninstallFile);
        }
    } catch (Exception e) {
        logger.error("Error removing properties for uninstalled extensions.", e);
    }
}